├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── etc ├── checkstyle │ ├── checkstyle.xml │ └── suppressions.xml ├── jenkins │ ├── build.sh │ ├── publish.sh │ └── test.sh ├── lint │ └── lint.xml ├── local.properties.tmpl ├── pmd │ └── pmd.xml ├── spotbugs │ └── spotbugs.xml └── studio │ └── cbl.xml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lib ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── couchbase │ │ └── lite │ │ ├── PlatformBaseTest.java │ │ └── utils │ │ └── Report.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── couchbase │ │ └── lite │ │ ├── ConsoleLogger.java │ │ ├── CouchbaseLite.java │ │ ├── NetworkReachabilityManager.java │ │ └── internal │ │ ├── AndroidExecutionService.java │ │ ├── CouchbaseLiteInternal.java │ │ ├── core │ │ └── CBLVersion.java │ │ └── replicator │ │ └── CBLWebSocket.java │ └── res │ ├── raw │ └── errors.json │ └── values │ └── strings.xml ├── settings.gradle ├── test ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── res │ └── values │ └── strings.xml └── tools ├── perftest ├── .gitignore ├── app │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ ├── androidTest │ │ └── java │ │ │ └── com │ │ │ └── couchbase │ │ │ └── perftest │ │ │ └── ExampleInstrumentedTest.java │ │ ├── main │ │ ├── AndroidManifest.xml │ │ ├── assets │ │ │ ├── doc.json │ │ │ ├── iTunesMusicLibrary.json │ │ │ └── iTunesMusicLibrary_s.json │ │ ├── java │ │ │ └── com │ │ │ │ └── couchbase │ │ │ │ └── perftest │ │ │ │ ├── Benchmark.java │ │ │ │ ├── DocPerfTest.java │ │ │ │ ├── DocSavePerfTest.java │ │ │ │ ├── MainActivity.java │ │ │ │ ├── PerfTest.java │ │ │ │ ├── PullPerfTest.java │ │ │ │ ├── PushPerfTest.java │ │ │ │ ├── QueryPerfTest.java │ │ │ │ ├── StopWatch.java │ │ │ │ ├── TestData.java │ │ │ │ ├── TunesPerfTest.java │ │ │ │ └── ZipUtils.java │ │ └── res │ │ │ ├── drawable-v24 │ │ │ └── ic_launcher_foreground.xml │ │ │ ├── drawable │ │ │ └── ic_launcher_background.xml │ │ │ ├── layout │ │ │ └── activity_main.xml │ │ │ ├── mipmap-anydpi-v26 │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ └── values │ │ │ ├── colors.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── test │ │ └── java │ │ └── com │ │ └── couchbase │ │ └── perftest │ │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle └── upgradetest ├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── couchbase │ │ └── upgradetest │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── couchbase │ │ │ └── upgradetest │ │ │ └── MainActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── couchbase │ └── upgradetest │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # Intellij 36 | *.iml 37 | .idea 38 | 39 | # Keystore files 40 | *.jks 41 | 42 | # External native build folder generated in Android Studio 2.2 and later 43 | .externalNativeBuild 44 | 45 | # Google Services (e.g. APIs or Firebase) 46 | google-services.json 47 | 48 | # Freeline 49 | freeline.py 50 | freeline/ 51 | freeline_project_description.json 52 | 53 | # Others 54 | .DS_Store 55 | 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | This repository is deprecated as of Couchbase Lite v2.8. 3 | Please refer to the [Community Edition Repository](https://github.com/couchbase/couchbase-lite-java-ce-root) 4 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // 2 | // build.gradle 3 | // 4 | // Copyright (c) 2018 Couchbase, Inc. All rights reserved. 5 | // 6 | // Licensed under the Couchbase License Agreement (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // https://info.couchbase.com/rs/302-GJY-034/images/2017-10-30_License_Agreement.pdf 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | // 17 | buildscript { 18 | ext { 19 | COMPILE_SDK_VERSION = 29 20 | BUILD_TOOLS_VERSION = "29.0.3" 21 | KOTLIN_VERSION = '1.3.70' 22 | JACOCO_VERSION = '0.8.4' 23 | 24 | PROJECT_DIR = "${projectDir}" 25 | ROOT_DIR = "${PROJECT_DIR}/.." 26 | } 27 | 28 | repositories { 29 | google() 30 | maven { url "https://plugins.gradle.org/m2/" } 31 | jcenter() 32 | } 33 | 34 | dependencies { 35 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$KOTLIN_VERSION" 36 | classpath 'com.android.tools.build:gradle:3.6.1' 37 | classpath "org.jacoco:org.jacoco.core:$JACOCO_VERSION" 38 | classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.8.3' 39 | classpath "com.github.spotbugs:spotbugs-gradle-plugin:3.0.0" 40 | } 41 | } 42 | 43 | task clean(type: Delete) { delete rootProject.buildDir } 44 | -------------------------------------------------------------------------------- /etc/checkstyle/suppressions.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /etc/jenkins/build.sh: -------------------------------------------------------------------------------- 1 | # 2 | # CI Build script for Enterprise Android 3 | # 4 | GROUP='com.couchbase.lite' 5 | PRODUCT='coucbase-lite-android' 6 | EDITION='community' 7 | 8 | # These versions must match the versions in lib/build.gradle 9 | NDK_VERSION='20.1.5948944' 10 | CMAKE_VERSION='3.10.2.4988404' 11 | 12 | MAVEN_URL="http://mobile.maven.couchbase.com/maven2/cimaven" 13 | 14 | 15 | function usage() { 16 | echo "Usage: $0 " 17 | exit 1 18 | } 19 | 20 | if [ "$#" -ne 2 ]; then 21 | usage 22 | fi 23 | 24 | SDK_HOME="$1" 25 | if [ -z "$SDK_HOME" ]; then 26 | usage 27 | fi 28 | 29 | BUILD_NUMBER="$2" 30 | if [ -z "$BUILD_NUMBER" ]; then 31 | usage 32 | fi 33 | 34 | SDK_MGR="${SDK_HOME}/tools/bin/sdkmanager" 35 | 36 | echo "======== BUILD Couchbase Lite Android, Community Edition v`cat ../version.txt`-${BUILD_NUMBER}" 37 | 38 | echo "======== Install Toolchain" 39 | yes | ${SDK_MGR} --licenses > /dev/null 2>&1 40 | ${SDK_MGR} --install 'build-tools;29.0.3' 41 | ${SDK_MGR} --install "cmake;${CMAKE_VERSION}" 42 | ${SDK_MGR} --install "ndk;${NDK_VERSION}" 43 | 44 | # The Jenkins script has already put passwords into local.properties 45 | cat <> local.properties 46 | sdk.dir=${SDK_HOME} 47 | ndk.dir=${SDK_HOME}/ndk/${NDK_VERSION} 48 | cmake.dir=${SDK_HOME}/cmake/${CMAKE_VERSION} 49 | EOF 50 | 51 | echo "======== Build" 52 | ./gradlew ciCheck -PbuildNumber="${BUILD_NUMBER}" || exit 1 53 | 54 | echo "======== Publish artifacts" 55 | ./gradlew ciPublish -PbuildNumber="${BUILD_NUMBER}" -PmavenUrl="${MAVEN_URL}" || exit 1 56 | 57 | echo "======== BUILD COMPLETE" 58 | -------------------------------------------------------------------------------- /etc/jenkins/publish.sh: -------------------------------------------------------------------------------- 1 | # 2 | # Promote the candidate build to an internal release 3 | # 4 | GROUP='com.couchbase.lite' 5 | PRODUCT='couchbase-lite-android' 6 | EDITION='community' 7 | 8 | MAVEN_URL="http://mobile.maven.couchbase.com/maven2/internalmaven" 9 | 10 | 11 | function usage() { 12 | echo "Usage: $0 " 13 | exit 1 14 | } 15 | 16 | if [ "$#" -ne 4 ]; then 17 | usage 18 | fi 19 | 20 | VERSION="$1" 21 | if [ -z "$VERSION" ]; then 22 | usage 23 | fi 24 | 25 | BUILD_NUMBER="$2" 26 | if [ -z "$BUILD_NUMBER" ]; then 27 | usage 28 | fi 29 | 30 | ARTIFACTS="$3" 31 | if [ -z "$ARTIFACTS" ]; then 32 | usage 33 | fi 34 | 35 | WORKSPACE="$4" 36 | if [ -z "$WORKSPACE" ]; then 37 | usage 38 | fi 39 | 40 | echo "======== Publish candidate build to internal maven" 41 | ## Really should promote the existing package, instead of re-publishing 42 | ## Something like this: 43 | ## curl -X POST -H "Content-Type: application/json" \ 44 | ## --data '{"API_Key": "", "groupName": "com.couchbase.lite", "packageName": "couchbase-lite-android", "version": "2.7.0-43", "fromFeed": "cimaven", "toFeed": "internalmaven"}' \ 45 | ## http://mobile.maven.couchbase.com/api/promotions/promote 46 | ## At present that call fails to promote the entire package (bad PK copying the source tar) 47 | ## so, for now, just republish the same bits. 48 | ./gradlew ciPublish -PbuildNumber=${BUILD_NUMBER} -PmavenUrl=${MAVEN_URL} || exit 1 49 | 50 | echo "======== Copy artifacts to staging directory" 51 | POM_FILE='pom.xml' 52 | cp lib/build/outputs/aar/*.aar "${ARTIFACTS}/" 53 | cp lib/build/libs/*.jar "${ARTIFACTS}/" 54 | cp -a lib/build/reports "${ARTIFACTS}" 55 | cp lib/build/publications/mavenJava/pom-default.xml "${ARTIFACTS}/${POM_FILE}" 56 | 57 | echo "======== Update package type in pom" 58 | ZIP_BUILD="${WORKSPACE}/zip-build" 59 | rm -rf "${ZIP_BUILD}" 60 | mkdir -p "${ZIP_BUILD}" 61 | pushd "${ZIP_BUILD}" 62 | cp "${ARTIFACTS}/${POM_FILE}" . || exit 1 63 | sed -i.bak "s#aar#pom#" "${POM_FILE}" || exit 1 64 | diff "${POM_FILE}" "${POM_FILE}.bak" 65 | 66 | echo "======== Fetch library dependencies" 67 | /home/couchbase/jenkins/tools/hudson.tasks.Maven_MavenInstallation/M3/bin/mvn install dependency:copy-dependencies || exit 1 68 | popd 69 | 70 | echo "======== Create zip" 71 | ZIP_STAGING="${WORKSPACE}/staging" 72 | rm -rf "${ZIP_STAGING}" 73 | mkdir -p "${ZIP_STAGING}" 74 | pushd "${ZIP_STAGING}" 75 | cp "${ZIP_BUILD}/target/dependency/"*.jar . || exit 1 76 | cp "${WORKSPACE}/product-texts/mobile/couchbase-lite/license/LICENSE_${EDITION}.txt" ./LICENSE.TXT || exit 1 77 | cp "${ARTIFACTS}/${PRODUCT}-${VERSION}-${BUILD_NUMBER}-release.aar" "./${PRODUCT}-${VERSION}.aar" || exit 1 78 | zip -r "${ARTIFACTS}/${PRODUCT}-${VERSION}-android_${EDITION}.zip" * || exit 1 79 | popd 80 | 81 | echo "======== PUBLICATION COMPLETE" 82 | 83 | -------------------------------------------------------------------------------- /etc/jenkins/test.sh: -------------------------------------------------------------------------------- 1 | # 2 | # Run automated tests 3 | # 4 | GROUP='com.couchbase.lite' 5 | PRODUCT='coucbase-lite-android' 6 | EDITION='community' 7 | 8 | 9 | function usage() { 10 | echo "Usage: $0 " 11 | exit 1 12 | } 13 | 14 | if [ "$#" -ne 2 ]; then 15 | usage 16 | fi 17 | 18 | BUILD_NUMBER="$1" 19 | if [ -z "$BUILD_NUMBER" ]; then 20 | usage 21 | fi 22 | 23 | REPORTS="$2" 24 | if [ -z "REPORTS" ]; then 25 | usage 26 | fi 27 | 28 | echo "======== Run automated tests on device: ${ANDROID_SERIAL}" 29 | ./gradlew ciTest --info --console=plain -PautomatedTests=true -PbuildNumber="${BUILD_NUMBER}" || exit 1 30 | 31 | echo "======== Copy test reports" 32 | cp -rp test/build/reports/* "${REPORTS}/" 33 | 34 | echo "======== TEST COMPLETE" 35 | -------------------------------------------------------------------------------- /etc/lint/lint.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /etc/local.properties.tmpl: -------------------------------------------------------------------------------- 1 | ## This is a template for the local.properties file that must 2 | # be at the root of each build, and must not be checked in to git 3 | # as it contains information specific to your local configuration. 4 | # 5 | # Location of the SDK. This is only used by Gradle. 6 | sdk.dir=${ANDROID_HOME} 7 | ndk.dir=${ANDROID_HOME}/ndk/20.1.5948944 8 | cmake.dir=${ANDROID_HOME}/cmake/3.10.2.4988404 9 | -------------------------------------------------------------------------------- /etc/pmd/pmd.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | CBL-Android 11 | 12 | .*/R.java 13 | .*/gen/.* 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | open 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | -------------------------------------------------------------------------------- /etc/spotbugs/spotbugs.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | 19 | # Comma separated list of annotations on tests that should NOT be run. 20 | #testFilter=com.couchbase.lite.utils.ReplicatorSystemTest 21 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/couchbase/couchbase-lite-android/f6213e837fd6e39108fe21c0e32def53b4e5634b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /lib/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /.cxx 3 | -------------------------------------------------------------------------------- /lib/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/hideki/java/android-sdk-macosx/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | 27 | 28 | ## OkHttp3 29 | #-dontwarn okhttp3.** 30 | #-dontwarn okio.** 31 | #-dontwarn javax.annotation.** 32 | #-dontwarn org.conscrypt.** 33 | ## A resource is loaded with a relative path so the package of this class must be preserved. 34 | #-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase 35 | # 36 | ## CBL2.x 37 | #-keep class com.couchbase.litecore.**{ *; } 38 | #-keep class com.couchbase.lite.**{ *; } 39 | 40 | -------------------------------------------------------------------------------- /lib/src/androidTest/java/com/couchbase/lite/PlatformBaseTest.java: -------------------------------------------------------------------------------- 1 | // 2 | // PlatformBaseTest.java 3 | // 4 | // Copyright (c) 2019 Couchbase, Inc All rights reserved. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | // 18 | package com.couchbase.lite; 19 | 20 | import android.support.test.InstrumentationRegistry; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.io.InputStream; 25 | 26 | import org.junit.After; 27 | import org.junit.Before; 28 | 29 | import com.couchbase.lite.internal.CouchbaseLiteInternal; 30 | import com.couchbase.lite.internal.ExecutionService; 31 | import com.couchbase.lite.internal.support.Log; 32 | 33 | 34 | /** 35 | * Platform test class for Android. 36 | */ 37 | public abstract class PlatformBaseTest implements PlatformTest { 38 | public static final String PRODUCT = "Android"; 39 | public static final String LEGAL_FILE_NAME_CHARS = "`~@#$%^&*()_+{}|\\][=-/.,<>?\":;'ABCDEabcde"; 40 | public static final String DB_EXTENSION = AbstractDatabase.DB_EXTENSION; 41 | 42 | public static void initCouchbase() { CouchbaseLite.init(InstrumentationRegistry.getTargetContext()); } 43 | 44 | public static void deinitCouchbase() { CouchbaseLiteInternal.reset(); } 45 | 46 | // this should probably go in the BaseTest but 47 | // there are several tests (C4 tests) that are not subclasses 48 | static { initCouchbase(); } 49 | 50 | 51 | private String tmpDirPath; 52 | 53 | // Before and After naming conventions 54 | @Before 55 | public void setUp() throws CouchbaseLiteException { } 56 | 57 | @After 58 | public void tearDown() { } 59 | 60 | // make a half-hearted attempt to set up file logging 61 | @Override 62 | public void setupFileLogging() { 63 | try { 64 | final FileLogger fileLogger = Database.log.getFile(); 65 | final File logDir = InstrumentationRegistry.getTargetContext().getExternalFilesDir("logs"); 66 | 67 | if (logDir == null) { throw new IllegalStateException("Cannot find external files directory"); } 68 | 69 | fileLogger.setConfig(new LogFileConfiguration(logDir.getCanonicalPath())); 70 | 71 | fileLogger.setLevel(LogLevel.INFO); 72 | } 73 | catch (IOException ignore) { } 74 | } 75 | 76 | @Override 77 | public String getDatabaseDirectoryPath() { return CouchbaseLiteInternal.getDbDirectoryPath(); } 78 | 79 | @Override 80 | public String getScratchDirectoryPath(String name) { 81 | if (tmpDirPath == null) { tmpDirPath = CouchbaseLiteInternal.getTmpDirectoryPath(); } 82 | 83 | try { return new File(tmpDirPath, name).getCanonicalPath(); } 84 | catch (IOException e) { throw new RuntimeException("Could not open tmp directory: " + name, e); } 85 | } 86 | 87 | @Override 88 | public InputStream getAsset(String asset) { 89 | try { return CouchbaseLiteInternal.getContext().getAssets().open(asset); } 90 | catch (IOException ignore) { } 91 | return null; 92 | } 93 | 94 | @Override 95 | public void executeAsync(long delayMs, Runnable task) { 96 | ExecutionService executionService = CouchbaseLiteInternal.getExecutionService(); 97 | executionService.postDelayedOnExecutor(delayMs, executionService.getMainExecutor(), task); 98 | } 99 | 100 | @Override 101 | public void reloadStandardErrorMessages() { 102 | Log.initLogging(CouchbaseLiteInternal.loadErrorMessages(InstrumentationRegistry.getTargetContext())); 103 | 104 | } 105 | 106 | private static String getSystemProperty(String name) throws Exception { 107 | Class systemPropertyClazz = Class.forName("android.os.SystemProperties"); 108 | return (String) systemPropertyClazz 109 | .getMethod("get", String.class) 110 | .invoke(systemPropertyClazz, new Object[] {name}); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /lib/src/androidTest/java/com/couchbase/lite/utils/Report.java: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2019 Couchbase, Inc All rights reserved. 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | package com.couchbase.lite.utils; 17 | 18 | import android.support.annotation.NonNull; 19 | import android.support.annotation.Nullable; 20 | import android.util.Log; 21 | 22 | import java.util.Locale; 23 | 24 | import com.couchbase.lite.LogLevel; 25 | 26 | 27 | /** 28 | * Platform console logging utility for tests 29 | */ 30 | public final class Report { 31 | private Report() {} 32 | 33 | public static void log(@NonNull LogLevel level, @NonNull String message) { 34 | Report.log(level, message, (Throwable) null); 35 | } 36 | 37 | public static void log(@NonNull LogLevel level, @NonNull String template, Object... args) { 38 | Report.log(level, String.format(Locale.ENGLISH, template, args)); 39 | } 40 | 41 | public static void log(@NonNull LogLevel level, @NonNull String message, @Nullable Throwable err) { 42 | final String domain = "CouchbaseLite/Test"; 43 | switch (level) { 44 | case DEBUG: 45 | Log.d(domain, message); 46 | break; 47 | case VERBOSE: 48 | Log.v(domain, message); 49 | break; 50 | case INFO: 51 | Log.i(domain, message); 52 | break; 53 | case WARNING: 54 | Log.w(domain, message); 55 | break; 56 | case ERROR: 57 | Log.e(domain, message, err); 58 | break; 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /lib/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 18 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /lib/src/main/java/com/couchbase/lite/ConsoleLogger.java: -------------------------------------------------------------------------------- 1 | // 2 | // ConsoleLogger.java 3 | // 4 | // Copyright (c) 2018 Couchbase, Inc All rights reserved. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | // 18 | package com.couchbase.lite; 19 | 20 | import android.support.annotation.NonNull; 21 | import android.util.Log; 22 | 23 | 24 | /** 25 | * A class that sends log messages to Android's system log, available via 'logcat'. 26 | */ 27 | public final class ConsoleLogger extends AbstractConsoleLogger { 28 | @Override 29 | protected void doLog(LogLevel level, @NonNull LogDomain domain, @NonNull String message) { 30 | final String tag = "CouchbaseLite/" + domain.toString(); 31 | switch (level) { 32 | case DEBUG: 33 | Log.d(tag, message); 34 | break; 35 | case VERBOSE: 36 | Log.v(tag, message); 37 | break; 38 | case INFO: 39 | Log.i(tag, message); 40 | break; 41 | case WARNING: 42 | Log.w(tag, message); 43 | break; 44 | case ERROR: 45 | Log.e(tag, message); 46 | break; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /lib/src/main/java/com/couchbase/lite/CouchbaseLite.java: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2019 Couchbase, Inc All rights reserved. 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | package com.couchbase.lite; 17 | 18 | import android.content.Context; 19 | import android.support.annotation.NonNull; 20 | import android.support.annotation.Nullable; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | 25 | import com.couchbase.lite.internal.CouchbaseLiteInternal; 26 | 27 | 28 | public final class CouchbaseLite { 29 | // Utility class 30 | private CouchbaseLite() {} 31 | 32 | /** 33 | * Initialize CouchbaseLite library. This method MUST be called before using CouchbaseLite. 34 | */ 35 | public static void init(@NonNull Context ctxt) { init(ctxt, null); } 36 | 37 | /** 38 | * Initialize CouchbaseLite library. 39 | * This method allows specifying a root directory for CBL files. 40 | * Use this version with great caution. 41 | * 42 | * @param rootDirectory the root directory for CBL files 43 | */ 44 | public static void init(@NonNull Context ctxt, @Nullable File rootDirectory) { 45 | String rootDirPath = null; 46 | if (rootDirectory != null) { 47 | try { rootDirPath = rootDirectory.getCanonicalPath(); } 48 | catch (IOException e) { 49 | throw new IllegalArgumentException("Could not get path for directory: " + rootDirectory, e); 50 | } 51 | } 52 | 53 | CouchbaseLiteInternal.init(new MValueDelegate(), rootDirPath, ctxt); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /lib/src/main/java/com/couchbase/lite/NetworkReachabilityManager.java: -------------------------------------------------------------------------------- 1 | // 2 | // NetworkReachabilityManager.java 3 | // 4 | // Copyright (c) 2017 Couchbase, Inc All rights reserved. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | // 18 | package com.couchbase.lite; 19 | 20 | import android.content.BroadcastReceiver; 21 | import android.content.Context; 22 | import android.content.Intent; 23 | import android.content.IntentFilter; 24 | import android.net.ConnectivityManager; 25 | import android.net.NetworkInfo; 26 | 27 | import com.couchbase.lite.internal.CouchbaseLiteInternal; 28 | import com.couchbase.lite.internal.support.Log; 29 | 30 | 31 | /** 32 | * NOTE: https://developer.android.com/training/basics/network-ops/managing.html 33 | */ 34 | final class NetworkReachabilityManager extends AbstractNetworkReachabilityManager { 35 | 36 | private static final LogDomain DOMAIN = LogDomain.REPLICATOR; 37 | 38 | private class NetworkReceiver extends BroadcastReceiver { 39 | @Override 40 | public void onReceive(Context context, Intent intent) { 41 | if (!ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction()) || !listening) { return; } 42 | final boolean online = isOnline(context); 43 | Log.v(DOMAIN, "NetworkReceiver.onReceive() Online -> " + online); 44 | if (online) { notifyListenersNetworkReachable(); } 45 | else { notifyListenersNetworkUneachable(); } 46 | } 47 | } 48 | 49 | private final NetworkReceiver receiver; 50 | private final Context context; 51 | private boolean listening; 52 | 53 | NetworkReachabilityManager() { 54 | this.receiver = new NetworkReceiver(); 55 | this.context = CouchbaseLiteInternal.getContext(); 56 | 57 | this.listening = false; 58 | } 59 | 60 | /** 61 | * NOTE: startListening() method is called from addNetworkReachabilityListener() which is 62 | * synchronized. So this method is not necessary to be synchronized. 63 | */ 64 | @Override 65 | void startListening() { 66 | if (!listening) { 67 | final IntentFilter filter = new IntentFilter(); 68 | filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 69 | Log.v(DOMAIN, "%s: startListening() registering %s with context %s", this, receiver, context); 70 | context.registerReceiver(receiver, filter); 71 | listening = true; 72 | } 73 | } 74 | 75 | /** 76 | * NOTE: stopListening() method is called from removeNetworkReachabilityListener() which is 77 | * synchronized. So this method is not necessary to be synchronized. 78 | */ 79 | @Override 80 | void stopListening() { 81 | if (listening) { 82 | try { 83 | Log.v( 84 | DOMAIN, 85 | "%s: stopListening() unregistering %s with context %s", this, receiver, context); 86 | context.unregisterReceiver(receiver); 87 | } 88 | catch (Exception e) { 89 | Log.e( 90 | DOMAIN, 91 | "%s: stopListening() exception unregistering %s with context %s", 92 | e, 93 | this, 94 | receiver, 95 | context); 96 | } 97 | listening = false; 98 | } 99 | } 100 | 101 | private boolean isOnline(Context ctx) { 102 | final ConnectivityManager service = ((ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE)); 103 | if (service == null) { return false; } 104 | final NetworkInfo networkInfo = service.getActiveNetworkInfo(); 105 | return (networkInfo != null) && networkInfo.isConnected(); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /lib/src/main/java/com/couchbase/lite/internal/AndroidExecutionService.java: -------------------------------------------------------------------------------- 1 | // 2 | // ExecutionService.java 3 | // 4 | // Copyright (c) 2017 Couchbase, Inc All rights reserved. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | // 18 | package com.couchbase.lite.internal; 19 | 20 | import android.os.AsyncTask; 21 | import android.os.Handler; 22 | import android.os.Looper; 23 | import android.support.annotation.NonNull; 24 | 25 | import java.util.concurrent.Executor; 26 | import java.util.concurrent.RejectedExecutionException; 27 | import java.util.concurrent.ThreadPoolExecutor; 28 | 29 | import com.couchbase.lite.LogDomain; 30 | import com.couchbase.lite.internal.support.Log; 31 | import com.couchbase.lite.internal.utils.Preconditions; 32 | 33 | 34 | /** 35 | * ExecutionService for Android. 36 | */ 37 | public final class AndroidExecutionService extends AbstractExecutionService { 38 | 39 | //--------------------------------------------- 40 | // Types 41 | //--------------------------------------------- 42 | private static class CancellableTask implements Cancellable { 43 | private final Handler handler; 44 | private final Runnable task; 45 | 46 | private CancellableTask(@NonNull Handler handler, @NonNull Runnable task) { 47 | Preconditions.assertNotNull(handler, "handler"); 48 | Preconditions.assertNotNull(task, "task"); 49 | this.handler = handler; 50 | this.task = task; 51 | } 52 | 53 | @Override 54 | public void cancel() { handler.removeCallbacks(task); } 55 | } 56 | 57 | 58 | //--------------------------------------------- 59 | // Instance variables 60 | //--------------------------------------------- 61 | private final Handler mainHandler; 62 | private final Executor mainThreadExecutor; 63 | 64 | //--------------------------------------------- 65 | // Constructor 66 | //--------------------------------------------- 67 | public AndroidExecutionService() { 68 | super((ThreadPoolExecutor) AsyncTask.THREAD_POOL_EXECUTOR); 69 | mainHandler = new Handler(Looper.getMainLooper()); 70 | mainThreadExecutor = mainHandler::post; 71 | } 72 | 73 | //--------------------------------------------- 74 | // Public methods 75 | //--------------------------------------------- 76 | @NonNull 77 | @Override 78 | public Executor getMainExecutor() { return mainThreadExecutor; } 79 | 80 | /** 81 | * This runs a task on Android's main thread for just long enough to enough to enqueue the passed task 82 | * on the passed executor. It occupies space in the main looper's message queue 83 | * but takes no significant time processing, there. 84 | * If the target executor refuses the task, it is just dropped on the floor. 85 | * 86 | * @param delayMs delay before posting the task. There may be additional queue delays in the executor. 87 | * @param executor an executor on which to execute the task. 88 | * @param task the task to be executed. 89 | * @return a cancellable task 90 | */ 91 | @NonNull 92 | @Override 93 | public Cancellable postDelayedOnExecutor(long delayMs, @NonNull Executor executor, @NonNull Runnable task) { 94 | Preconditions.assertNotNull(executor, "executor"); 95 | Preconditions.assertNotNull(task, "task"); 96 | 97 | final Runnable delayedTask = () -> { 98 | try { executor.execute(task); } 99 | catch (CloseableExecutor.ExecutorClosedException e) { 100 | Log.w(LogDomain.DATABASE, "Scheduled on closed executor: " + task + ", " + executor); 101 | } 102 | catch (RejectedExecutionException e) { 103 | if (!throttled()) { dumpServiceState(executor, "after: " + delayMs, e); } 104 | } 105 | }; 106 | 107 | mainHandler.postDelayed(delayedTask, delayMs); 108 | 109 | return new CancellableTask(mainHandler, delayedTask); 110 | } 111 | 112 | /** 113 | * Best effort, delete the passed task (obtained from postDelayedOnExecutor, above) 114 | * from the wait queue. If it is already in the Executor, well, there you go. 115 | * 116 | * @param cancellableTask returned by a previous call to postDelayedOnExecutor. 117 | */ 118 | @Override 119 | public void cancelDelayedTask(@NonNull Cancellable cancellableTask) { 120 | Preconditions.assertNotNull(cancellableTask, "cancellableTask"); 121 | cancellableTask.cancel(); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /lib/src/main/java/com/couchbase/lite/internal/CouchbaseLiteInternal.java: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2019 Couchbase, Inc All rights reserved. 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | package com.couchbase.lite.internal; 17 | 18 | import android.content.Context; 19 | import android.support.annotation.GuardedBy; 20 | import android.support.annotation.NonNull; 21 | import android.support.annotation.Nullable; 22 | import android.support.annotation.VisibleForTesting; 23 | 24 | import java.io.File; 25 | import java.io.IOException; 26 | import java.io.InputStream; 27 | import java.lang.ref.SoftReference; 28 | import java.util.HashMap; 29 | import java.util.Map; 30 | import java.util.Objects; 31 | import java.util.Scanner; 32 | import java.util.concurrent.atomic.AtomicBoolean; 33 | import java.util.concurrent.atomic.AtomicReference; 34 | 35 | import org.json.JSONException; 36 | import org.json.JSONObject; 37 | 38 | import com.couchbase.lite.BuildConfig; 39 | import com.couchbase.lite.LogDomain; 40 | import com.couchbase.lite.R; 41 | import com.couchbase.lite.internal.core.C4Base; 42 | import com.couchbase.lite.internal.fleece.MValue; 43 | import com.couchbase.lite.internal.support.Log; 44 | import com.couchbase.lite.internal.utils.Preconditions; 45 | 46 | 47 | /** 48 | * Among the other things that this class attempts to abstract away, is access to the file system. 49 | * On both Android, and in a Web Container, file system access is pretty problematic. 50 | * Among other things, some code make the tacit assumption that there is a single root directory 51 | * that contains both a scratch (temp) directory and the database directory. The scratch directory 52 | * is also used, occasionally, as the home for log files. 53 | */ 54 | public final class CouchbaseLiteInternal { 55 | // Utility class 56 | private CouchbaseLiteInternal() {} 57 | 58 | private static final String LITECORE_JNI_LIBRARY = "LiteCoreJNI"; 59 | 60 | private static final String TEMP_DIR_NAME = "CouchbaseLiteTemp"; 61 | private static final String DB_DIR_NAME = ".couchbase"; 62 | 63 | private static final AtomicReference EXECUTION_SERVICE = new AtomicReference<>(); 64 | private static final AtomicReference> CONTEXT = new AtomicReference<>(); 65 | 66 | private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false); 67 | 68 | private static final Object LOCK = new Object(); 69 | 70 | private static volatile boolean debugging = BuildConfig.CBL_DEBUG; 71 | 72 | @GuardedBy("lock") 73 | private static String dbDirPath; 74 | @GuardedBy("lock") 75 | private static volatile String tmpDirPath; 76 | 77 | /** 78 | * Initialize CouchbaseLite library. This method MUST be called before using CouchbaseLite. 79 | */ 80 | public static void init( 81 | @NonNull MValue.Delegate mValueDelegate, 82 | @Nullable String rootDirectoryPath, 83 | @NonNull Context ctxt) { 84 | Preconditions.assertNotNull(mValueDelegate, "mValueDelegate"); 85 | Preconditions.assertNotNull(ctxt, "context"); 86 | 87 | if (INITIALIZED.getAndSet(true)) { return; } 88 | 89 | CONTEXT.set(new SoftReference<>(ctxt.getApplicationContext())); 90 | 91 | // Splitting initialization and registration is not really necessary here. 92 | // Do it to maintain code parity with the Java version, where it is necessary. 93 | initDirectories(rootDirectoryPath); 94 | 95 | System.loadLibrary(LITECORE_JNI_LIBRARY); 96 | 97 | if (debugging) { C4Base.debug(); } 98 | 99 | setC4TmpDirPath(); 100 | 101 | MValue.registerDelegate(mValueDelegate); 102 | 103 | Log.initLogging(loadErrorMessages(ctxt)); 104 | } 105 | 106 | public static boolean isDebugging() { return debugging; } 107 | 108 | /** 109 | * This method is not part of the public API. 110 | * It will be removed in a future release. 111 | */ 112 | public static ExecutionService getExecutionService() { 113 | ExecutionService executionService = EXECUTION_SERVICE.get(); 114 | if (executionService == null) { 115 | EXECUTION_SERVICE.compareAndSet(null, new AndroidExecutionService()); 116 | executionService = EXECUTION_SERVICE.get(); 117 | } 118 | return executionService; 119 | } 120 | 121 | public static void requireInit(String message) { 122 | if (!INITIALIZED.get()) { 123 | throw new IllegalStateException(message + ". Did you forget to call CouchbaseLite.init()?"); 124 | } 125 | } 126 | 127 | @NonNull 128 | public static Context getContext() { 129 | requireInit("Application context not initialized"); 130 | final SoftReference contextRef = CONTEXT.get(); 131 | 132 | final Context ctxt = contextRef.get(); 133 | if (ctxt == null) { throw new IllegalStateException("Context is null"); } 134 | 135 | return ctxt; 136 | } 137 | 138 | @NonNull 139 | public static String makeDbPath(@Nullable String rootDir) { 140 | requireInit("Can't create DB path"); 141 | return verifyDir((rootDir != null) ? new File(rootDir) : new File(getContext().getFilesDir(), DB_DIR_NAME)); 142 | } 143 | 144 | @NonNull 145 | public static String makeTmpPath(@Nullable String rootDir) { 146 | requireInit("Can't create tmp dir path"); 147 | final File dir = (rootDir != null) 148 | ? new File(rootDir, TEMP_DIR_NAME) 149 | : getContext().getExternalFilesDir(TEMP_DIR_NAME); 150 | if (dir == null) { throw new IllegalStateException("Tmp dir root is null"); } 151 | return verifyDir(dir); 152 | } 153 | 154 | public static void setupDirectories(@Nullable String rootDirPath) { 155 | requireInit("Can't set root directory"); 156 | 157 | synchronized (LOCK) { 158 | // remember the current tmp dir 159 | final String tmpPath = tmpDirPath; 160 | 161 | initDirectories(rootDirPath); 162 | 163 | // if the temp dir has changed, tell C4Base 164 | if (!Objects.equals(tmpPath, tmpDirPath)) { setC4TmpDirPath(); } 165 | } 166 | } 167 | 168 | @NonNull 169 | public static String getDbDirectoryPath() { 170 | requireInit("Database directory not initialized"); 171 | synchronized (LOCK) { return dbDirPath; } 172 | } 173 | 174 | @NonNull 175 | public static String getTmpDirectoryPath() { 176 | requireInit("Database directory not initialized"); 177 | synchronized (LOCK) { return tmpDirPath; } 178 | } 179 | 180 | @VisibleForTesting 181 | public static void reset() { INITIALIZED.set(false); } 182 | 183 | @VisibleForTesting 184 | @NonNull 185 | public static Map loadErrorMessages(@NonNull Context ctxt) { 186 | final Map errorMessages = new HashMap<>(); 187 | 188 | try (InputStream is = ctxt.getResources().openRawResource(R.raw.errors)) { 189 | final JSONObject root = new JSONObject(new Scanner(is, "UTF-8").useDelimiter("\\A").next()); 190 | final Iterable errors = root::keys; 191 | for (String error : errors) { errorMessages.put(error, root.getString(error)); } 192 | } 193 | catch (IOException | JSONException e) { 194 | Log.e(LogDomain.DATABASE, "Failed to load error messages!", e); 195 | } 196 | 197 | return errorMessages; 198 | } 199 | 200 | @NonNull 201 | private static String verifyDir(@NonNull File dir) { 202 | IOException err = null; 203 | try { 204 | if ((dir.exists() && dir.isDirectory()) || dir.mkdirs()) { return dir.getCanonicalPath(); } 205 | } 206 | catch (IOException e) { err = e; } 207 | 208 | throw new IllegalStateException("Cannot create or access directory at " + dir, err); 209 | } 210 | 211 | private static void initDirectories(@Nullable String rootDirPath) { 212 | final String dbPath = makeDbPath(rootDirPath); 213 | final String tmpPath = makeTmpPath(rootDirPath); 214 | 215 | synchronized (LOCK) { 216 | tmpDirPath = tmpPath; 217 | dbDirPath = dbPath; 218 | } 219 | } 220 | 221 | private static void setC4TmpDirPath() { 222 | synchronized (LOCK) { C4Base.setTempDir(tmpDirPath); } 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /lib/src/main/java/com/couchbase/lite/internal/core/CBLVersion.java: -------------------------------------------------------------------------------- 1 | // 2 | // CBLVersion.java 3 | // 4 | // Copyright (c) 2018 Couchbase, Inc All rights reserved. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | // 18 | package com.couchbase.lite.internal.core; 19 | 20 | import android.os.Build; 21 | 22 | import java.util.Locale; 23 | import java.util.concurrent.atomic.AtomicReference; 24 | 25 | import com.couchbase.lite.BuildConfig; 26 | 27 | @SuppressWarnings({"PMD.ClassNamingConventions", "PMD.FieldNamingConventions"}) 28 | public final class CBLVersion { 29 | private CBLVersion() {} 30 | 31 | private static final String USER_AGENT = "CouchbaseLite/%s (%s) %s"; 32 | private static final String VERSION_INFO = "CouchbaseLite Android v%s (%s at %s) on %s"; 33 | private static final String LIB_INFO = "%s/%s, Commit/%s Core/%s"; 34 | private static final String SYS_INFO = "Java; Android %s; %s"; 35 | 36 | private static final AtomicReference userAgent = new AtomicReference<>(); 37 | private static final AtomicReference versionInfo = new AtomicReference<>(); 38 | private static final AtomicReference libInfo = new AtomicReference<>(); 39 | private static final AtomicReference sysInfo = new AtomicReference<>(); 40 | 41 | public static String getUserAgent() { 42 | String agent = userAgent.get(); 43 | 44 | if (agent == null) { 45 | agent = String.format( 46 | Locale.ENGLISH, 47 | USER_AGENT, 48 | BuildConfig.VERSION_NAME, 49 | getSysInfo(), 50 | getLibInfo()); 51 | 52 | userAgent.compareAndSet(null, agent); 53 | } 54 | 55 | return agent; 56 | } 57 | 58 | // This is information about this library build. 59 | public static String getVersionInfo() { 60 | String info = versionInfo.get(); 61 | if (info == null) { 62 | info = String.format( 63 | Locale.ENGLISH, 64 | VERSION_INFO, 65 | BuildConfig.VERSION_NAME, 66 | getLibInfo(), 67 | BuildConfig.BUILD_TIME, 68 | getSysInfo()); 69 | 70 | versionInfo.compareAndSet(null, info); 71 | } 72 | 73 | return info; 74 | } 75 | 76 | // This is information about this library build. 77 | public static String getLibInfo() { 78 | String info = libInfo.get(); 79 | if (info == null) { 80 | info = String.format( 81 | Locale.ENGLISH, 82 | LIB_INFO, 83 | (BuildConfig.ENTERPRISE) ? "EE" : "CE", 84 | BuildConfig.BUILD_TYPE, 85 | BuildConfig.BUILD_COMMIT, 86 | C4.getVersion()); 87 | 88 | libInfo.compareAndSet(null, info); 89 | } 90 | 91 | return info; 92 | } 93 | 94 | // This is information about the Android on which we are running. 95 | public static String getSysInfo() { 96 | String info = sysInfo.get(); 97 | 98 | if (info == null) { 99 | final String version = Build.VERSION.RELEASE; // "1.0" or "3.4b5" 100 | final String model = Build.MODEL; 101 | 102 | info = String.format( 103 | Locale.ENGLISH, 104 | SYS_INFO, 105 | (version.length() <= 0) ? "unknown" : version, 106 | (model.length() <= 0) ? "unknown" : model); 107 | 108 | sysInfo.compareAndSet(null, info); 109 | } 110 | 111 | return info; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /lib/src/main/java/com/couchbase/lite/internal/replicator/CBLWebSocket.java: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2019 Couchbase, Inc All rights reserved. 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | package com.couchbase.lite.internal.replicator; 17 | 18 | import android.os.Build; 19 | import android.support.annotation.NonNull; 20 | import android.support.annotation.RequiresApi; 21 | import android.system.ErrnoException; 22 | 23 | import java.io.EOFException; 24 | import java.net.ConnectException; 25 | import java.net.SocketException; 26 | import java.net.URISyntaxException; 27 | import java.security.GeneralSecurityException; 28 | import java.util.Map; 29 | 30 | import com.couchbase.lite.internal.core.C4Constants; 31 | 32 | 33 | public class CBLWebSocket extends AbstractCBLWebSocket { 34 | // Posix errno values with Android. 35 | // from sysroot/usr/include/asm-generic/errno.h 36 | private static final int ECONNRESET = 104; // java.net.SocketException 37 | private static final int ECONNREFUSED = 111; // java.net.ConnectException 38 | 39 | 40 | public CBLWebSocket( 41 | long handle, 42 | String scheme, 43 | String hostname, 44 | int port, 45 | String path, 46 | Map options) 47 | throws GeneralSecurityException, URISyntaxException { 48 | super(handle, scheme, hostname, port, path, options); 49 | } 50 | 51 | @SuppressWarnings("PMD.CollapsibleIfStatements") 52 | protected boolean handleClose(@NonNull Throwable error) { 53 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 54 | if (checkErrnoException(error)) { return true; } 55 | } 56 | 57 | // ConnectException 58 | if (error instanceof ConnectException) { 59 | closed(C4Constants.ErrorDomain.POSIX, ECONNREFUSED, null); 60 | return true; 61 | } 62 | 63 | // SocketException 64 | else if (error instanceof SocketException) { 65 | closed(C4Constants.ErrorDomain.POSIX, ECONNRESET, null); 66 | return true; 67 | } 68 | 69 | // EOFException 70 | if (error instanceof EOFException) { 71 | closed(C4Constants.ErrorDomain.POSIX, ECONNRESET, null); 72 | return true; 73 | } 74 | 75 | return false; 76 | } 77 | 78 | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) 79 | private boolean checkErrnoException(@NonNull Throwable error) { 80 | Throwable cause = error.getCause(); 81 | if (cause == null) { return false; } 82 | 83 | cause = cause.getCause(); 84 | if (!(cause instanceof ErrnoException)) { return false; } 85 | 86 | closed(C4Constants.ErrorDomain.POSIX, ((ErrnoException) cause).errno, null); 87 | 88 | return true; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /lib/src/main/res/raw/errors.json: -------------------------------------------------------------------------------- 1 | {"CreateDBDirectoryFailed": "Unable to create database directory.", "CloseDBFailedReplications": "Cannot close the database. Please stop all of the replicators before closing the database.", "CloseDBFailedQueryListeners": "Cannot close the database. Please remove all of the query listeners before closing the database.", "DeleteDBFailedReplications": "Cannot delete the database. Please stop all of the replicators before closing the database.", "DeleteDBFailedQueryListeners": "Cannot delete the database. Please remove all of the query listeners before closing the database.", "DeleteDocFailedNotSaved": "Cannot delete a document that has not yet been saved.", "DocumentNotFound": "The document doesn't exist in the database.", "DocumentAnotherDatabase": "Cannot operate on a document from another database.", "BlobDifferentDatabase": "A document contains a blob that was saved to a different database. The save operation cannot complete.", "BlobContentNull": "No data available to write for install. Please ensure that all blobs in the document have non-null content.", "ResolvedDocContainsNull": "Resolved document has a null body.", "ResolvedDocFailedLiteCore": "LiteCore failed resolving conflict.", "ResolvedDocWrongDb": "Resolved document's database %1$s is different from expected database %2$s.", "DBClosed": "Attempt to perform an operation on a closed database.", "NoDocumentRevision": "No revision data on the document!", "FragmentPathNotExist": "Specified fragment path does not exist in object; cannot set value.", "InvalidCouchbaseObjType": "%1$s is not a valid type. You may only pass %2$s, Blob, a one-dimensional array or a dictionary whose members are one of the preceding types.", "InvalidValueToBeDeserialized": "Non-string or null key in data to be deserialized.", "BlobContainsNoData": "Blob has no data available.", "NotFileBasedURL": "%1$s must be a file-based URL.", "BlobReadStreamNotOpen": "Stream is not open.", "CannotSetLogLevel": "Cannot set logging level without a configuration.", "InvalidSchemeURLEndpoint": "Invalid scheme for URLEndpoint url (%1$s). It must be either 'ws:' or 'wss:'.", "InvalidEmbeddedCredentialsInURL": "Embedded credentials in a URL (username:password@url) are not allowed. Use the BasicAuthenticator class instead.", "ReplicatorNotStopped": "Replicator is not stopped. Resetting checkpoint is only allowed when the replicator is in the stopped state.", "QueryParamNotAllowedContainCollections": "Query parameters are not allowed to contain collections.", "MissASforJoin": "Missing AS clause for JOIN.", "MissONforJoin": "Missing ON statement for JOIN.", "ExpressionsMustBeIExpressionOrString": "Expressions must either be %1$s or String.", "InvalidExpressionValueBetween": "Invalid expression value for expression of Between(%1$s).", "ResultSetAlreadyEnumerated": "This result set has already been enumerated. Please re-execute the original query.", "ExpressionsMustContainOnePlusElement": "%1$s expressions must contain at least one element.", "DuplicateSelectResultName": "Duplicate select result named %1$s.", "NoAliasInJoin": "The default database must have an alias in order to use a JOIN statement (Make sure your data source uses the As() function).", "InvalidQueryDBNull": "Invalid query: The database is null.", "InvalidQueryMissingSelectOrFrom": "Invalid query: missing Select or From.", "PullOnlyPendingDocIDs": "Pending Document IDs are not supported on pull-only replicators."} -------------------------------------------------------------------------------- /lib/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | CouchbaseLite 3 | 4 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | // This project contains two distinct applications: 2 | // 1) the CBL-Android-EE source and the code to build, unit-test and publish it to maven 3 | // 2) an independent application that runs automated tests on the application build in #1 4 | // 5 | // The two apps are mutually exclusive: the test app is built and run only by CI machines 6 | // during the release process. All other work in this repo will use only the "lib" module. 7 | // Separating the two prevents confusing build failures, in the test app, while working 8 | // with the library. 9 | // The crazy hack below could be avoided by separating the test app into a separate project. 10 | // The only arguments for *not* doing this is that separating the two would require 11 | // separate directories for test projects (separate git repos?) and keeping the build scripts 12 | // for the test projects in sync 13 | // 14 | 15 | if (!hasProperty("automatedTests") || !automatedTests.toBoolean()) { 16 | // normal source development 17 | include ':lib' 18 | } else { 19 | // the test application 20 | include ':test' 21 | } 22 | -------------------------------------------------------------------------------- /test/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /test/build.gradle: -------------------------------------------------------------------------------- 1 | // 2 | // build.gradle 3 | // 4 | // Copyright (c) 2017, 2018, 2019 Couchbase, Inc All rights reserved. 5 | // 6 | // Licensed under the Couchbase License Agreement (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // https://info.couchbase.com/rs/302-GJY-034/images/2017-10-30_License_Agreement.pdf 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | // 17 | 18 | // ---------------------------------------------------------------- 19 | // Constants 20 | // ---------------------------------------------------------------- 21 | ext { 22 | CBL_GROUP = 'com.couchbase.lite' 23 | 24 | BUILD_VERSION = file("$ROOT_DIR/version.txt").text.trim() 25 | BUILD_NUMBER = (!project.hasProperty("buildNumber")) ? "SNAPSHOT" : buildNumber 26 | 27 | REPORTS_DIR = "${buildDir}/reports" 28 | CBL_CORE_DIR = "${ROOT_DIR}/couchbase-lite-core" 29 | CBL_JAVA_DIR = "${ROOT_DIR}/couchbase-lite-java/lib" 30 | CBL_ANDROID_DIR = "${PROJECT_DIR}" 31 | REPORTS_DIR = "${buildDir}/reports" 32 | } 33 | 34 | // comma separated list of annotations for tests that should not be run. 35 | def TEST_FILTER = (!project.hasProperty("testFilter")) ? null : testFilter 36 | 37 | // ---------------------------------------------------------------- 38 | // Build 39 | // ---------------------------------------------------------------- 40 | apply plugin: 'com.android.library' 41 | apply plugin: 'kotlin-android' 42 | 43 | group = CBL_GROUP 44 | version = BUILD_VERSION 45 | 46 | android { 47 | compileSdkVersion COMPILE_SDK_VERSION 48 | buildToolsVersion BUILD_TOOLS_VERSION 49 | 50 | defaultConfig { 51 | minSdkVersion 19 52 | targetSdkVersion 27 53 | versionCode 1 54 | versionName BUILD_VERSION 55 | 56 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 57 | if (TEST_FILTER != null) { 58 | testInstrumentationRunnerArguments notAnnotation: TEST_FILTER 59 | } 60 | } 61 | 62 | compileOptions { 63 | targetCompatibility 1.8 64 | sourceCompatibility 1.8 65 | } 66 | 67 | sourceSets { 68 | androidTest { 69 | java.srcDirs = [ 70 | "${CBL_ANDROID_DIR}/lib/src/androidTest/java", // android specific codes 71 | "${CBL_JAVA_DIR}/src/shared/test/java" // shared java tests 72 | ] 73 | assets.srcDirs = [ 74 | "${CBL_CORE_DIR}/C/tests/data", // lite-core test assets 75 | "${CBL_JAVA_DIR}/src/shared/test/assets" // shared assets 76 | ] 77 | } 78 | } 79 | } 80 | 81 | repositories { 82 | mavenLocal() 83 | maven { url "http://mobile.maven.couchbase.com/maven2/cimaven/" } 84 | google() 85 | jcenter() 86 | } 87 | 88 | dependencies { 89 | implementation "com.couchbase.lite:couchbase-lite-android:${BUILD_VERSION}-${BUILD_NUMBER}" 90 | 91 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$KOTLIN_VERSION" 92 | 93 | testImplementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$KOTLIN_VERSION" 94 | testImplementation 'junit:junit:4.12' 95 | 96 | androidTestImplementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$KOTLIN_VERSION" 97 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 98 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 99 | } 100 | 101 | 102 | // ---------------------------------------------------------------- 103 | // Tasks 104 | // ---------------------------------------------------------------- 105 | 106 | // This target requires specifying properties "buildNumber" and "automatedTests". 107 | // See settings.gradle for explanation. 108 | task ciTest(dependsOn: ['connectedDebugAndroidTest']) 109 | -------------------------------------------------------------------------------- /test/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /test/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 18 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /test/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | CBLAndroidEE Automated Tests 3 | 4 | -------------------------------------------------------------------------------- /tools/perftest/.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # Intellij 36 | .idea 37 | *.iml 38 | 39 | # Keystore files 40 | *.jks 41 | 42 | # External native build folder generated in Android Studio 2.2 and later 43 | .externalNativeBuild 44 | 45 | # Google Services (e.g. APIs or Firebase) 46 | google-services.json 47 | 48 | # Freeline 49 | freeline.py 50 | freeline/ 51 | freeline_project_description.json 52 | 53 | # Others 54 | .DS_Store 55 | 56 | # Test file 57 | perfdb.cblite2.zip 58 | -------------------------------------------------------------------------------- /tools/perftest/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /tools/perftest/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | defaultConfig { 6 | applicationId "com.couchbase.perftest" 7 | minSdkVersion 19 8 | targetSdkVersion 26 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | implementation fileTree(dir: 'libs', include: ['*.jar']) 23 | implementation 'com.android.support:appcompat-v7:26.1.0' 24 | implementation 'com.android.support.constraint:constraint-layout:1.0.2' 25 | testImplementation 'junit:junit:4.12' 26 | androidTestImplementation 'com.android.support.test:runner:1.0.1' 27 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' 28 | implementation 'com.google.code.gson:gson:2.8.2' 29 | implementation 'com.couchbase.lite:couchbase-lite-android:2.1.0-105' 30 | } 31 | -------------------------------------------------------------------------------- /tools/perftest/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /tools/perftest/app/src/androidTest/java/com/couchbase/perftest/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.couchbase.perftest", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/assets/doc.json: -------------------------------------------------------------------------------- 1 | { 2 | "$hs": { 3 | "account": "UrbanGourmet", 4 | "channels": [ 5 | "UrbanGourmet::Manufacturer::f08250d9-8a09-4c41-95c9-f738fe010edc", 6 | "UrbanGourmet::Manufacturer::*" 7 | ], 8 | "create": [ 9 | "UrbanGourmet@ADMIN", 10 | "UrbanGourmet@REP", 11 | "UrbanGourmet@DIRECT" 12 | ], 13 | "delete": [ 14 | "UrbanGourmet@ADMIN", 15 | "UrbanGourmet@REP", 16 | "UrbanGourmet@DIRECT" 17 | ], 18 | "type": "UrbanGourmet::Item", 19 | "update": [ 20 | "UrbanGourmet@ADMIN", 21 | "UrbanGourmet@REP", 22 | "UrbanGourmet@DIRECT" 23 | ] 24 | }, 25 | "$schema": "", 26 | "account": "UrbanGourmet", 27 | "barcode": null, 28 | "category": "879c8561-b58c-4aa8-a51e-f6332ddd3869", 29 | "categoryPosition": 7, 30 | "conditionalData": { 31 | }, 32 | "ctime": "2017-06-01T18:35:03.832468Z", 33 | "ctimeOnServer": "2017-06-01T18:35:03.832468Z", 34 | "entityType": "Item", 35 | "externalID": null, 36 | "hasGeneratedSKU": false, 37 | "isHidden": false, 38 | "isHiddenForCustomers": false, 39 | "isImplicitlyHidden": false, 40 | "isImplicitlyHiddenForCustomers": false, 41 | "longDesc": "Lush and creamy, with a mild, earthy flavor, eggplant has the most velvety texture in the vegetable family. It's high in healthy fiber. We love it sliced, brushed with olive oil and salt, and grilled or roasted. We also love it breaded, fried, and smothered in fried onions. Come to think of it, we just plain love it.\n\nOrganic, Locally grown in New York State", 42 | "minQty": 1, 43 | "mtime": "2018-02-21T16:06:43.413129Z", 44 | "mtimeOnServer": "2018-02-21T16:06:43.413129Z", 45 | "multQty": 1, 46 | "name": "Organic Eggplant", 47 | "objID": 148, 48 | "owner": "4b864d77-c3fb-4d15-8eaf-280ffe706c04", 49 | "pricingUnit": "lb", 50 | "pricingUnitPerSaleUnit": "25.000000000", 51 | "saleUnit": "Box", 52 | "sku": "3445", 53 | "unitPrice": "1.99" 54 | } 55 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/assets/iTunesMusicLibrary_s.json: -------------------------------------------------------------------------------- 1 | {"Year":1997,"Kind":"AAC audio file","Genre":"Alternative","Name":"Syndir Guos (Opinberun Frelsarans)","Track ID":18022,"Total Time":465684,"Album":"Von","Persistent ID":"A2F441604C2B4919","Date Added":"2008-08-07T05:18:51.000Z","Track Type":"Remote","Artist":"Sigur Rós","Size":11614406,"Sample Rate":44100,"Track Number":11,"Bit Rate":256,"Date Modified":"2011-02-26T20:03:37.000Z"} 2 | {"Track Type":"Remote","Compilation":true,"Sample Rate":44100,"Disc Number":1,"Kind":"Purchased AAC audio file","Clean":true,"Track Count":21,"Date Added":"2007-09-27T18:13:42.000Z","Name":"Ricochet Effect","Purchased":true,"Size":9618677,"Composer":"Uros Umek","Track Number":19,"Album Artist":"John Digweed","Artist":"Umek","Year":2007,"Bit Rate":256,"Disc Count":1,"Artwork Count":1,"Track ID":10150,"Total Time":596306,"Genre":"Trance","Date Modified":"2007-09-28T03:18:47.000Z","Album":"Renaissance: Transitions, Vol. 3","Album Rating":60,"Album Rating Computed":true,"Persistent ID":"2B96FAA0C3EB61E2"} 3 | {"Track Type":"Remote","Kind":"MPEG audio file","Play Date UTC":"2010-07-17T01:38:04.000Z","Track Count":13,"Date Added":"2008-08-07T04:16:25.000Z","Name":"Rayman13","Track Number":1,"Size":69150329,"Year":1999,"Artist":"DJ sneJ","Bit Rate":128,"Play Count":1,"Artwork Count":1,"Play Date":3362150284,"Track ID":13688,"Total Time":4310622,"Rating":100,"Album Rating Computed":true,"Date Modified":"2008-07-28T01:42:17.000Z","Album":"Rayman13","Album Rating":100,"Persistent ID":"162F9D43BCCBB18D"} 4 | {"Track Type":"File","Skip Date":"2013-11-12T05:12:30.000Z","Sample Rate":44100,"Kind":"MPEG audio file","Play Date UTC":"2014-06-07T04:41:52.000Z","Track Count":10,"Date Added":"2013-11-12T03:46:01.000Z","Name":"In The Ditch","Track Number":8,"Size":6418465,"Composer":"Gang of Four","Location":"file:\/\/localhost\/Music\/Gang%20of%20Four\/Solid%20Gold\/08%20In%20The%20Ditch.mp3","Year":1981,"Artist":"Gang of Four","Skip Count":1,"Bit Rate":192,"Library Folder Count":1,"Play Count":1,"Artwork Count":1,"Play Date":3484935712,"Track ID":9284,"Total Time":262844,"Genre":"Post-Punk","Date Modified":"2013-11-12T04:12:21.000Z","Album":"Solid Gold","Album Rating":80,"Album Rating Computed":true,"File Folder Count":4,"Persistent ID":"8C31040A8C68F46E"} 5 | {"Track Type":"Remote","Kind":"MPEG audio file","Play Date UTC":"2009-09-14T16:31:01.000Z","Track Number":9,"Date Added":"2009-09-11T00:16:20.000Z","Name":"Stealth Dub","Year":1987,"Size":11701951,"Artist":"Blind Idiot God","Bit Rate":320,"Play Count":2,"Artwork Count":1,"Grouping":"Borrowed","Play Date":3335765461,"Track ID":26480,"Total Time":283794,"Album Rating Computed":true,"Genre":"Metal","Album":"Blind Idiot God","Album Rating":60,"Date Modified":"2009-11-26T21:38:10.000Z","Persistent ID":"6753AEE891C0F11A"} 6 | {"Track Type":"Remote","Sample Rate":44100,"Kind":"AAC audio file","Track Count":14,"Date Added":"2008-08-07T05:16:14.000Z","Name":"Domesticated","Track Number":11,"Size":2372315,"Year":2001,"Artist":"Dealership","Bit Rate":256,"Artwork Count":1,"Track ID":13328,"Total Time":128940,"Album Rating Computed":true,"Date Modified":"2011-02-26T19:10:36.000Z","Genre":"Alternative","Album":"TV Highway To The Stars","Album Rating":100,"Persistent ID":"AEC228597C2174FF"} 7 | {"Track Type":"Remote","Disc Number":1,"Kind":"MPEG audio file","Play Date UTC":"2009-11-09T01:53:17.000Z","Track Number":3,"Date Added":"2009-07-02T05:49:06.000Z","Name":"Pulp","Year":1990,"Size":6386190,"Album Artist":"Godflesh","Artist":"Godflesh","Bit Rate":197,"Disc Count":1,"Play Count":10,"Artwork Count":1,"Rating":80,"Track ID":26120,"Play Date":3340551197,"Total Time":256600,"Genre":"Metal","Date Modified":"2009-11-26T21:25:00.000Z","Album":"Streetcleaner","Album Rating":80,"Album Rating Computed":true,"Persistent ID":"B6E071F5A7F2824D"} 8 | {"Track Type":"File","Sample Rate":44100,"Disc Number":1,"Kind":"MPEG audio file","File Type":1297106739,"Track Count":15,"Date Added":"2012-08-19T23:25:57.000Z","Name":"Blues Happy","Track Number":4,"Size":942781,"Composer":"Speech","Location":"file:\/\/localhost\/Music\/Arrested%20Development\/3%20Years,%205%20Months%20&%202%20Days%20In%20The%20Life%20Of.._\/04%20Blues%20Happy.mp3","Year":1992,"Artist":"Arrested Development","Library Folder Count":1,"Disc Count":1,"Bit Rate":163,"Track ID":6652,"Total Time":46080,"Genre":"Rap","Date Modified":"2012-08-19T23:26:02.000Z","Album":"3 Years, 5 Months & 2 Days In The Life Of...","File Folder Count":4,"Persistent ID":"114A7D757528A912"} 9 | {"Track Type":"Remote","Kind":"MPEG audio file","Comments":"Visit http:\/\/antiqueshade.bandcamp.com","Play Date UTC":"2012-01-30T00:43:30.000Z","Track Number":5,"Date Added":"2012-01-26T04:23:31.000Z","Name":"delta blues","Year":2011,"Size":6274105,"Artist":"antique shade","Bit Rate":232,"Play Count":2,"Artwork Count":1,"Play Date":3410703810,"Track ID":29658,"Total Time":206785,"Rating":80,"Album Rating Computed":true,"Date Modified":"2012-01-26T13:22:02.000Z","Album":"homeward sounds EP","Album Rating":80,"Persistent ID":"1313AC5ACE0AA905"} 10 | {"Track Type":"Remote","Sample Rate":44100,"Kind":"AAC audio file","Play Date UTC":"2014-05-11T01:53:42.000Z","Track Count":17,"Date Added":"2008-08-07T05:21:43.000Z","Name":"•Icehouse","Track Number":1,"Size":6414929,"Year":1980,"Artist":"Icehouse","Bit Rate":256,"Play Count":2,"Artwork Count":1,"Play Date":3482592822,"Track ID":21786,"Total Time":262870,"Rating":80,"Date Modified":"2011-02-26T19:29:37.000Z","Genre":"Electronic","Album":"Flowers (Remastered)","Album Rating":80,"Album Rating Computed":true,"Persistent ID":"58EA35B976718EC1"} 11 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/Benchmark.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class Benchmark { 8 | private StopWatch _st; 9 | private List _times; 10 | 11 | public Benchmark() { 12 | _st = new StopWatch(); 13 | _times = new ArrayList<>(); 14 | } 15 | 16 | public void start() { 17 | _st.reset(); 18 | } 19 | 20 | // sec 21 | public double elapsed() { 22 | return _st.elapsedSec(); 23 | } 24 | 25 | // sec 26 | public double stop() { 27 | double t = _st.elapsedSec(); 28 | _times.add(t); 29 | return t; 30 | } 31 | 32 | public void empty() { 33 | _times.clear(); 34 | } 35 | 36 | public void sort() { 37 | Collections.sort(_times); 38 | } 39 | 40 | public double median() { 41 | sort(); 42 | if(_times.isEmpty()) return 0.0; 43 | return _times.get(_times.size() / 2); 44 | } 45 | 46 | public double average() { 47 | sort(); 48 | if(_times.isEmpty()) return 0.0; 49 | int n = _times.size(); 50 | double total = 0; 51 | for (double t : _times) 52 | total += t; 53 | return total / n; 54 | } 55 | 56 | public double stddev() { 57 | if(_times.isEmpty()) return 0.0; 58 | double avg = average(); 59 | int n = _times.size(); 60 | double total = 0; 61 | for (double t : _times) 62 | total += Math.pow(t - avg, 2); 63 | return Math.sqrt(total / n); 64 | } 65 | 66 | public double[] range() { 67 | sort(); 68 | if(_times.isEmpty()) 69 | return new double[]{0.0,0.0}; 70 | else 71 | return new double[]{_times.get(0), _times.get(_times.size() - 1)}; 72 | } 73 | 74 | public void printReport(String items) { 75 | printReport(1.0, items); 76 | } 77 | 78 | public void printReport(double scale, String items) { 79 | double[] r = range(); 80 | final String[] kTimeScales = {"sec", "ms", "µs", "ns"}; 81 | double avg = average(); 82 | String scaleName = ""; 83 | for (int i = 0; i < kTimeScales.length; i++) { 84 | scaleName = kTimeScales[i]; 85 | if (avg * scale >= 1.0) 86 | break; 87 | scale *= 1000; 88 | } 89 | if (items != null) 90 | scaleName += "/" + items; 91 | System.err.print(String.format("Range: %7.3f ... %7.3f %s, Average: %7.3f, median: %7.3f, std dev: %5.3g\n", 92 | r[0] * scale, r[1] * scale, scaleName, avg * scale, median() * scale, stddev() * scale)); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/DocPerfTest.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | 6 | import com.couchbase.lite.CouchbaseLiteException; 7 | import com.couchbase.lite.DatabaseConfiguration; 8 | import com.couchbase.lite.MutableDocument; 9 | 10 | public class DocPerfTest extends PerfTest { 11 | 12 | public DocPerfTest(Context context, DatabaseConfiguration dbConfig) { 13 | super(context, dbConfig); 14 | } 15 | 16 | @Override 17 | protected void test() { 18 | final int revs = 10000; 19 | Log.i(TAG, String.format("--- Creating %d revisions ---", revs)); 20 | measure(revs, "revision", new Runnable() { 21 | @Override 22 | public void run() { 23 | addRevisions(revs); 24 | } 25 | }); 26 | } 27 | 28 | void addRevisions(final int revisions) { 29 | try { 30 | db.inBatch(new Runnable() { 31 | @Override 32 | public void run() { 33 | try { 34 | MutableDocument mDoc = new MutableDocument("doc"); 35 | updateDoc(mDoc, revisions); 36 | //updateDocWithGetDocument(mDoc, revisions); 37 | } catch (CouchbaseLiteException e) { 38 | e.printStackTrace(); 39 | } 40 | 41 | } 42 | }); 43 | } catch (CouchbaseLiteException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | 48 | void updateDoc(MutableDocument doc, final int revisions) throws CouchbaseLiteException { 49 | for (int i = 0; i < revisions; i++) { 50 | doc.setValue("count", i); 51 | db.save(doc); 52 | } 53 | } 54 | 55 | void updateDocWithGetDocument(MutableDocument doc, final int revisions) throws CouchbaseLiteException { 56 | for (int i = 0; i < revisions; i++) { 57 | doc.setValue("count", i); 58 | db.save(doc); 59 | doc = db.getDocument("doc").toMutable(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/DocSavePerfTest.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | 6 | import com.couchbase.lite.CouchbaseLiteException; 7 | import com.couchbase.lite.DatabaseConfiguration; 8 | import com.couchbase.lite.Document; 9 | import com.couchbase.lite.MutableDocument; 10 | 11 | import java.util.Locale; 12 | import java.util.Map; 13 | 14 | public class DocSavePerfTest extends PerfTest { 15 | protected DocSavePerfTest(Context context, DatabaseConfiguration dbConfig) { 16 | super(context, dbConfig); 17 | } 18 | 19 | @Override 20 | protected void test() { 21 | final int numDocs = 1000; // 1K docs in one batch 22 | final int numUpdates = 10000; // 10K updates -> 10M revisions 23 | 24 | 25 | Log.i(TAG, String.format("--- Creating %d documents and update %s times ---", numDocs, numUpdates)); 26 | measure(numDocs * numUpdates, "save", new Runnable() { 27 | @Override 28 | public void run() { 29 | for (int i = 0; i < numUpdates; i++) { 30 | Log.w(TAG, String.format("Test Batch %d of %d", i, numUpdates)); 31 | Map> products = TestData.generateProducts(numDocs); 32 | saveDocument("Products", products); 33 | } 34 | } 35 | }); 36 | } 37 | 38 | void saveDocument(final String documentStoreName, final Map> newDocs) { 39 | Log.w(TAG, String.format("Saving document list (%d) in document store {%s}...", newDocs.size(), documentStoreName)); 40 | try { 41 | db.inBatch(new Runnable() { 42 | @Override 43 | public void run() { 44 | for (String key : newDocs.keySet()) { 45 | String docID = getDocID(documentStoreName, key); 46 | MutableDocument doc = updateMutableDocument(docID, newDocs.get(key)); 47 | try { 48 | db.save(doc); 49 | } catch (CouchbaseLiteException e) { 50 | e.printStackTrace(); 51 | } 52 | } 53 | } 54 | }); 55 | } catch (CouchbaseLiteException e) { 56 | e.printStackTrace(); 57 | } 58 | } 59 | 60 | private String getDocID(String documentStoreName, String id) { 61 | return String.format(Locale.ENGLISH, "%s|%s", documentStoreName.toLowerCase(), id); 62 | } 63 | 64 | private MutableDocument updateMutableDocument(String docID, Map value) { 65 | Document doc = db.getDocument(docID); 66 | MutableDocument mutableDoc = null; 67 | if (doc != null) { 68 | mutableDoc = doc.toMutable(); 69 | mutableDoc.setData(value); 70 | } else 71 | mutableDoc = new MutableDocument(docID, value); 72 | return mutableDoc; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.view.View; 6 | 7 | import com.couchbase.lite.DatabaseConfiguration; 8 | 9 | public class MainActivity extends AppCompatActivity { 10 | @Override 11 | protected void onCreate(Bundle savedInstanceState) { 12 | super.onCreate(savedInstanceState); 13 | setContentView(R.layout.activity_main); 14 | 15 | View.OnClickListener clickListener = new View.OnClickListener() { 16 | @Override 17 | public void onClick(View view) { 18 | switch (view.getId()) { 19 | case R.id.btnDocPerf: 20 | new DocPerfTest(MainActivity.this, new DatabaseConfiguration(MainActivity.this)).run(); 21 | break; 22 | case R.id.btnTunesPerf: 23 | new TunesPerfTest(MainActivity.this, new DatabaseConfiguration(MainActivity.this)).run(); 24 | break; 25 | case R.id.btnQuryPerf: 26 | new QueryPerfTest(MainActivity.this, new DatabaseConfiguration(MainActivity.this)).run(); 27 | break; 28 | case R.id.btnPushPerf: 29 | new PushPerfTest(MainActivity.this, new DatabaseConfiguration(MainActivity.this)).run(); 30 | break; 31 | case R.id.btnPullPerf: 32 | new PullPerfTest(MainActivity.this, new DatabaseConfiguration(MainActivity.this)).run(); 33 | break; 34 | case R.id.btnDocSavePerf: 35 | new DocSavePerfTest(MainActivity.this, new DatabaseConfiguration(MainActivity.this)).run(); 36 | break; 37 | } 38 | } 39 | }; 40 | 41 | findViewById(R.id.btnDocPerf).setOnClickListener(clickListener); 42 | findViewById(R.id.btnTunesPerf).setOnClickListener(clickListener); 43 | findViewById(R.id.btnQuryPerf).setOnClickListener(clickListener); 44 | findViewById(R.id.btnPushPerf).setOnClickListener(clickListener); 45 | findViewById(R.id.btnPullPerf).setOnClickListener(clickListener); 46 | findViewById(R.id.btnDocSavePerf).setOnClickListener(clickListener); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/PerfTest.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import android.content.Context; 4 | import android.os.AsyncTask; 5 | import android.util.Log; 6 | 7 | import com.couchbase.lite.CouchbaseLiteException; 8 | import com.couchbase.lite.Database; 9 | import com.couchbase.lite.DatabaseConfiguration; 10 | 11 | import java.io.File; 12 | import java.io.InputStream; 13 | 14 | public abstract class PerfTest { 15 | protected static final String TAG = "PerfTest"; 16 | protected static final String DB_NAME = "perfdb"; 17 | protected Context context; 18 | protected Database db; 19 | protected String dbName; 20 | protected DatabaseConfiguration dbConfig; 21 | 22 | protected abstract void test(); 23 | 24 | protected PerfTest(Context context, DatabaseConfiguration dbConfig) { 25 | this.context = context; 26 | this.dbConfig = dbConfig; 27 | this.dbName = DB_NAME; 28 | } 29 | 30 | public void run() { 31 | new AsyncTask() { 32 | @Override 33 | protected Void doInBackground(Void... voids) { 34 | Log.i(TAG, String.format("====== %s ======", PerfTest.this.getClass().getSimpleName())); 35 | setUp(); 36 | test(); 37 | tearDown(); 38 | return null; 39 | } 40 | }.execute(); 41 | } 42 | 43 | protected void setUp() { 44 | openDB(); 45 | } 46 | 47 | protected void tearDown() { 48 | closeDB(); 49 | } 50 | 51 | protected void measure(int count, String unit, Runnable runnable) { 52 | Benchmark b = new Benchmark(); 53 | final int reps = 10; 54 | for (int i = 0; i < reps; i++) { 55 | eraseDB(); 56 | b.start(); 57 | runnable.run(); 58 | double t = b.stop(); // sec 59 | System.err.print(String.format("%.03f ", t)); 60 | } 61 | System.err.print("(sec)\n"); 62 | b.printReport(null); 63 | if (count > 1) 64 | b.printReport(1.0 / count, unit); 65 | } 66 | 67 | protected void openDB() { 68 | try { 69 | db = new Database(dbName, dbConfig); 70 | } catch (CouchbaseLiteException e) { 71 | e.printStackTrace(); 72 | } 73 | } 74 | 75 | protected void closeDB() { 76 | db = closeDB(db); 77 | } 78 | 79 | protected Database closeDB(Database _db) { 80 | if (_db != null) { 81 | try { 82 | _db.close(); 83 | } catch (CouchbaseLiteException e) { 84 | e.printStackTrace(); 85 | } 86 | } 87 | return null; 88 | } 89 | 90 | protected void eraseDB() { 91 | closeDB(); 92 | try { 93 | Database.delete(dbName, new File(dbConfig.getDirectory())); 94 | } catch (CouchbaseLiteException e) { 95 | e.printStackTrace(); 96 | } 97 | openDB(); 98 | } 99 | 100 | protected void reopenDB() { 101 | closeDB(); 102 | openDB(); 103 | } 104 | 105 | protected InputStream getAsset(String name) { 106 | return this.getClass().getResourceAsStream("/assets/" + name); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/PullPerfTest.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | 6 | import com.couchbase.lite.DatabaseConfiguration; 7 | import com.couchbase.lite.Replicator; 8 | import com.couchbase.lite.ReplicatorChange; 9 | import com.couchbase.lite.ReplicatorChangeListener; 10 | import com.couchbase.lite.ReplicatorConfiguration; 11 | import com.couchbase.lite.URLEndpoint; 12 | 13 | import java.net.URI; 14 | import java.net.URISyntaxException; 15 | import java.util.concurrent.CountDownLatch; 16 | 17 | public class PullPerfTest extends PerfTest { 18 | static final int kNumIterations = 1; 19 | Benchmark bench = new Benchmark(); 20 | static final int docs = 100 * 1000; // 100K 21 | static final String SG_URL = "ws://10.17.0.201:4984/db"; 22 | 23 | protected PullPerfTest(Context context, DatabaseConfiguration dbConfig) { 24 | super(context, dbConfig); 25 | } 26 | 27 | @Override 28 | protected void setUp() { 29 | super.setUp(); 30 | 31 | eraseDB(); 32 | 33 | if (db.getCount() != 0) 34 | Log.e(TAG, "DB size is invalid. size: " + db.getCount()); 35 | } 36 | 37 | @Override 38 | protected void test() { 39 | for (int i = 0; i < kNumIterations; i++) { 40 | System.err.print(String.format("Starting iteration #%d...\n", i + 1)); 41 | 42 | bench.start(); 43 | 44 | URI uri = null; 45 | try { 46 | uri = new URI(SG_URL); 47 | } catch (URISyntaxException e) { 48 | e.printStackTrace(); 49 | return; 50 | } 51 | URLEndpoint endpoint = new URLEndpoint(uri); 52 | ReplicatorConfiguration config = new ReplicatorConfiguration(db, endpoint) 53 | .setReplicatorType(ReplicatorConfiguration.ReplicatorType.PULL); 54 | Replicator replicator = new Replicator(config); 55 | final CountDownLatch latch = new CountDownLatch(1); 56 | replicator.addChangeListener(new ReplicatorChangeListener() { 57 | @Override 58 | public void changed(ReplicatorChange change) { 59 | if (change.getStatus().getActivityLevel().equals(Replicator.ActivityLevel.STOPPED)) 60 | latch.countDown(); 61 | } 62 | }); 63 | replicator.start(); 64 | try { 65 | latch.await(); 66 | } catch (InterruptedException e) { 67 | e.printStackTrace(); 68 | return; 69 | } 70 | 71 | if (db.getCount() != docs) 72 | Log.e(TAG, "DB size is invalid. size: " + db.getCount()); 73 | 74 | double t = bench.stop(); 75 | System.err.print(String.format("PULL %d documents in %.06f sec\n", docs, t)); 76 | } 77 | 78 | System.err.print(String.format("PULL %5d docs: ", docs)); 79 | bench.printReport(null); 80 | System.err.print(" "); 81 | bench.printReport(1.0 / docs, "doc"); 82 | System.err.print(String.format(" Rate: %.0f docs/sec\n", docs / bench.median())); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/PushPerfTest.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | 6 | import com.couchbase.lite.CouchbaseLiteException; 7 | import com.couchbase.lite.DatabaseConfiguration; 8 | import com.couchbase.lite.MutableDocument; 9 | import com.couchbase.lite.Replicator; 10 | import com.couchbase.lite.ReplicatorChange; 11 | import com.couchbase.lite.ReplicatorChangeListener; 12 | import com.couchbase.lite.ReplicatorConfiguration; 13 | import com.couchbase.lite.URLEndpoint; 14 | import com.google.gson.Gson; 15 | import com.google.gson.reflect.TypeToken; 16 | 17 | import java.io.IOException; 18 | import java.io.InputStreamReader; 19 | import java.lang.reflect.Type; 20 | import java.net.URI; 21 | import java.net.URISyntaxException; 22 | import java.util.Locale; 23 | import java.util.Map; 24 | import java.util.concurrent.CountDownLatch; 25 | import java.util.concurrent.atomic.AtomicInteger; 26 | 27 | 28 | public class PushPerfTest extends PerfTest { 29 | static final int kNumIterations = 1; 30 | Benchmark bench = new Benchmark(); 31 | static final int docs = 100 * 1000; // 100K 32 | static final String SG_URL = "ws://10.17.0.201:4984/db"; 33 | 34 | protected PushPerfTest(Context context, DatabaseConfiguration dbConfig) { 35 | super(context, dbConfig); 36 | } 37 | 38 | @Override 39 | protected void setUp() { 40 | super.setUp(); 41 | 42 | closeDB(); 43 | 44 | try { 45 | // 1M document database 46 | ZipUtils.unzip(getAsset("perfdb.cblite2.zip"), context.getFilesDir()); 47 | } catch (IOException e) { 48 | e.printStackTrace(); 49 | } 50 | 51 | openDB(); 52 | 53 | // Log.i(TAG, String.format("--- Creating %d documents ---", docs)); 54 | // createDocs(docs); 55 | 56 | if (db.getCount() != docs) 57 | Log.e(TAG, "DB size is invalid. size: " + db.getCount()); 58 | } 59 | 60 | @Override 61 | protected void test() { 62 | 63 | for (int i = 0; i < kNumIterations; i++) { 64 | System.err.print(String.format("Starting iteration #%d...\n", i + 1)); 65 | 66 | bench.start(); 67 | 68 | URI uri = null; 69 | try { 70 | uri = new URI(SG_URL); 71 | } catch (URISyntaxException e) { 72 | e.printStackTrace(); 73 | return; 74 | } 75 | URLEndpoint endpoint = new URLEndpoint(uri); 76 | ReplicatorConfiguration config = new ReplicatorConfiguration(db, endpoint) 77 | .setReplicatorType(ReplicatorConfiguration.ReplicatorType.PUSH); 78 | Replicator replicator = new Replicator(config); 79 | final CountDownLatch latch = new CountDownLatch(1); 80 | replicator.addChangeListener(new ReplicatorChangeListener() { 81 | @Override 82 | public void changed(ReplicatorChange change) { 83 | if (change.getStatus().getActivityLevel().equals(Replicator.ActivityLevel.STOPPED)) 84 | latch.countDown(); 85 | } 86 | }); 87 | replicator.start(); 88 | try { 89 | latch.await(); 90 | } catch (InterruptedException e) { 91 | e.printStackTrace(); 92 | return; 93 | } 94 | 95 | double t = bench.stop(); 96 | System.err.print(String.format("Push %d documents in %.06f sec\n", docs, t)); 97 | } 98 | 99 | System.err.print(String.format("Push %5d docs: ", docs)); 100 | bench.printReport(null); 101 | System.err.print(" "); 102 | bench.printReport(1.0 / docs, "doc"); 103 | System.err.print(String.format(" Rate: %.0f docs/sec\n", docs / bench.median())); 104 | 105 | 106 | } 107 | 108 | 109 | void createDocs(final int docs) { 110 | final Map map; 111 | Type type = new TypeToken>() { 112 | }.getType(); 113 | InputStreamReader isr = new InputStreamReader(getAsset("doc.json")); 114 | try { 115 | Gson gson = new Gson(); 116 | map = gson.fromJson(isr, type); 117 | } finally { 118 | try { 119 | isr.close(); 120 | } catch (IOException e) { 121 | e.printStackTrace(); 122 | return; 123 | } 124 | } 125 | 126 | final AtomicInteger atomic = new AtomicInteger(0); 127 | for (int j = 0; j < docs / 1000; j++) { 128 | try { 129 | db.inBatch(new Runnable() { 130 | @Override 131 | public void run() { 132 | for (int i = 0; i < 1000; i++) { 133 | String docID = String.format(Locale.ENGLISH, "doc-%08d", atomic.incrementAndGet()); 134 | MutableDocument doc = new MutableDocument(docID); 135 | doc.setInt("index", atomic.get()); 136 | doc.setData(map); 137 | try { 138 | db.save(doc); 139 | } catch (CouchbaseLiteException e) { 140 | e.printStackTrace(); 141 | } 142 | } 143 | } 144 | }); 145 | } catch (CouchbaseLiteException e) { 146 | e.printStackTrace(); 147 | } 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/QueryPerfTest.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | 6 | import com.couchbase.lite.CouchbaseLiteException; 7 | import com.couchbase.lite.DataSource; 8 | import com.couchbase.lite.DatabaseConfiguration; 9 | import com.couchbase.lite.Meta; 10 | import com.couchbase.lite.MutableDocument; 11 | import com.couchbase.lite.Query; 12 | import com.couchbase.lite.QueryBuilder; 13 | import com.couchbase.lite.Result; 14 | import com.couchbase.lite.ResultSet; 15 | import com.couchbase.lite.SelectResult; 16 | 17 | import java.io.IOException; 18 | import java.util.Locale; 19 | import java.util.concurrent.atomic.AtomicInteger; 20 | 21 | 22 | public class QueryPerfTest extends PerfTest { 23 | static final int kNumIterations = 10; 24 | Benchmark bench = new Benchmark(); 25 | final int docs = 1000 * 1000; 26 | 27 | protected QueryPerfTest(Context context, DatabaseConfiguration dbConfig) { 28 | super(context, dbConfig); 29 | } 30 | 31 | @Override 32 | protected void setUp() { 33 | super.setUp(); 34 | 35 | closeDB(); 36 | 37 | try { 38 | // 1M document database 39 | ZipUtils.unzip(getAsset("perfdb.cblite2.zip"), context.getFilesDir()); 40 | } catch (IOException e) { 41 | e.printStackTrace(); 42 | } 43 | 44 | openDB(); 45 | 46 | // Log.i(TAG, String.format("--- Creating %d documents ---", docs)); 47 | // createDocs(docs); 48 | 49 | if (db.getCount() != docs) 50 | Log.e(TAG, "DB size is invalid. size: " + db.getCount()); 51 | } 52 | 53 | @Override 54 | protected void test() { 55 | for (int i = 0; i < kNumIterations; i++) { 56 | System.err.print(String.format("Starting iteration #%d...\n", i + 1)); 57 | int count = query(); 58 | if (count != docs) 59 | Log.e(TAG, String.format(Locale.ENGLISH, "Query result count does not match! Actual -> %; expected -> %d", count, docs)); 60 | } 61 | System.err.print(String.format("Query %5d docs: ", docs)); 62 | bench.printReport(null); 63 | System.err.print(" "); 64 | bench.printReport(1.0 / docs, "doc"); 65 | System.err.print(String.format(" Rate: %.0f docs/sec\n", docs / bench.median())); 66 | } 67 | 68 | int query() { 69 | int count = 0; 70 | bench.start(); 71 | Query q = QueryBuilder.select(SelectResult.expression(Meta.id)) 72 | .from(DataSource.database(db)); 73 | ResultSet rs = null; 74 | try { 75 | rs = q.execute(); 76 | } catch (CouchbaseLiteException e) { 77 | e.printStackTrace(); 78 | } 79 | for (Result r : rs) { 80 | count++; 81 | } 82 | double t = bench.stop(); 83 | System.err.print(String.format("Query %d documents in %.06f sec\n", count, t)); 84 | return count; 85 | } 86 | 87 | void createDocs(final int docs) { 88 | final AtomicInteger atomic = new AtomicInteger(0); 89 | for (int j = 0; j < docs / 1000; j++) { 90 | try { 91 | db.inBatch(new Runnable() { 92 | @Override 93 | public void run() { 94 | for (int i = 0; i < 1000; i++) { 95 | String docID = String.format(Locale.ENGLISH, "doc-%08d", atomic.incrementAndGet()); 96 | MutableDocument doc = new MutableDocument(docID); 97 | doc.setInt("index", atomic.get()); 98 | try { 99 | db.save(doc); 100 | } catch (CouchbaseLiteException e) { 101 | e.printStackTrace(); 102 | } 103 | } 104 | } 105 | }); 106 | } catch (CouchbaseLiteException e) { 107 | e.printStackTrace(); 108 | } 109 | } 110 | } 111 | } 112 | 113 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/StopWatch.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import java.util.Locale; 4 | 5 | public class StopWatch { 6 | //private long startTime = 0; // nano seconds 7 | //private long stopTime = 0; 8 | 9 | private long _total = 0L; // nano seconds 10 | private long _start = 0L; 11 | private boolean _running = false; 12 | 13 | public StopWatch() { 14 | this(true); 15 | } 16 | 17 | public StopWatch(boolean running) { 18 | if (running) 19 | start(); 20 | } 21 | 22 | public void start() { 23 | if (!_running) { 24 | _running = true; 25 | _start = System.nanoTime(); 26 | } 27 | } 28 | 29 | public void stop() { 30 | if (_running) { 31 | _running = false; 32 | _total += (System.nanoTime() - _start); 33 | } 34 | } 35 | 36 | public void reset() { 37 | _total = 0L; 38 | if (_running) 39 | _start = System.nanoTime(); 40 | } 41 | 42 | // nano sec 43 | public double elapsed() { 44 | long e = _total; 45 | if (_running) 46 | e += (System.nanoTime() - _start); 47 | return e; 48 | } 49 | 50 | // milli sec 51 | public double elapsedMS() { 52 | return elapsed() / 1000000.0; 53 | } 54 | 55 | // sec 56 | public double elapsedSec() { 57 | return elapsed() / 1000000000.0; 58 | } 59 | 60 | public String printReport(String what, long count, String item) { 61 | return String.format(Locale.ENGLISH, "%s; %d %s (took %.3f ms)", what, count, item, elapsedMS()); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/TestData.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.perftest; 2 | 3 | import java.util.HashMap; 4 | import java.util.Locale; 5 | import java.util.Map; 6 | 7 | public class TestData { 8 | static Map> generateProducts(int numDocs) { 9 | Map> items = new HashMap<>(); 10 | for (int i = 0; i < numDocs; i++) { 11 | String prodNum = String.format(Locale.ENGLISH, "%08d", i); 12 | Map item = new HashMap<>(); 13 | item.put("ProdNum", prodNum); 14 | item.put("ProdType", "1001"); 15 | item.put("IsInvCtrl", true); 16 | item.put("ProdSubType", ""); 17 | item.put("UPCUnitCode", ""); 18 | item.put("Price", 100.00); 19 | item.put("Mfg", ""); 20 | item.put("ModelNum", ""); 21 | item.put("IsBatch", false); 22 | item.put("IsSerialized", false); 23 | Map dict = new HashMap<>(); 24 | dict.put("en", "This is the English translation of the product description"); 25 | dict.put("es", "This is the Spanish translation of the product description"); 26 | item.put("Desc", dict); 27 | items.put(prodNum, item); 28 | } 29 | return items; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/java/com/couchbase/perftest/ZipUtils.java: -------------------------------------------------------------------------------- 1 | // 2 | // ZipUtils.java 3 | // 4 | // Copyright (c) 2017 Couchbase, Inc All rights reserved. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | // 18 | package com.couchbase.perftest; 19 | 20 | import java.io.File; 21 | import java.io.FileOutputStream; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.util.zip.ZipEntry; 25 | import java.util.zip.ZipInputStream; 26 | 27 | public class ZipUtils { 28 | public static void unzip(InputStream in, File destination) throws IOException { 29 | byte[] buffer = new byte[1024]; 30 | ZipInputStream zis = new ZipInputStream(in); 31 | ZipEntry ze = zis.getNextEntry(); 32 | while (ze != null) { 33 | String fileName = ze.getName(); 34 | File newFile = new File(destination, fileName); 35 | if (ze.isDirectory()) { 36 | newFile.mkdirs(); 37 | } else { 38 | new File(newFile.getParent()).mkdirs(); 39 | FileOutputStream fos = new FileOutputStream(newFile); 40 | int len; 41 | while ((len = zis.read(buffer)) > 0) { 42 | fos.write(buffer, 0, len); 43 | } 44 | fos.close(); 45 | } 46 | ze = zis.getNextEntry(); 47 | } 48 | zis.closeEntry(); 49 | zis.close(); 50 | in.close(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 | 71 | 76 | 81 | 86 | 91 | 96 | 101 | 106 | 111 | 116 | 121 | 126 | 131 | 136 | 141 | 146 | 151 | 156 | 161 | 166 | 171 | 172 | -------------------------------------------------------------------------------- /tools/perftest/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 |