├── .gitignore ├── .gitmodules ├── CONTRIBUTING.md ├── LICENSE.TXT ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── libs └── td_collator_so.jar ├── release └── upload_android_artifacts.sh ├── settings.gradle.example └── src ├── main ├── java │ └── com │ │ └── couchbase │ │ └── lite │ │ └── javascript │ │ ├── JavaScriptReplicationFilterCompiler.java │ │ ├── JavaScriptViewCompiler.java │ │ ├── ReplicationFilterBlockRhino.java │ │ ├── ViewMapBlockRhino.java │ │ ├── ViewReduceBlockRhino.java │ │ ├── scopes │ │ ├── GlobalScope.java │ │ ├── MapGlobalScope.java │ │ └── ReduceGlobalScope.java │ │ └── wrapper │ │ └── CustomWrapFactory.java └── res │ ├── drawable-hdpi │ └── ic_launcher.png │ ├── drawable-mdpi │ └── ic_launcher.png │ ├── drawable-xhdpi │ └── ic_launcher.png │ ├── values-v11 │ └── styles.xml │ ├── values-v14 │ └── styles.xml │ └── values │ ├── strings.xml │ └── styles.xml └── test ├── assets └── test.properties └── java └── com └── couchbase └── lite ├── ReplicationFilterTestCase.java └── javascript ├── JavaScriptTestCase.java ├── PerformanceTestCase.java └── helper ├── EmitPair.java └── MockEmiter.java /.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | *.iml 3 | /.DS_Store 4 | local.properties 5 | \#* 6 | *~ 7 | .#* 8 | \#*\# 9 | *.class 10 | .idea 11 | .gradle 12 | settings.gradle 13 | 14 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libraries/couchbase-lite-java-core"] 2 | path = libraries/couchbase-lite-java-core 3 | url = https://github.com/couchbase/couchbase-lite-java-core.git 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We hate bugs, but we love bug reports! And we're grateful to our developers who exercise Couchbase Lite and the Couchbase Sync Gateway in new and unexpected ways and help us work out the kinks. 2 | 3 | We also want to hear about your ideas for new features and improvements. You can file those in the issue trackers too. 4 | 5 | And while we welcome questions, **we prefer to answer questions on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/mobile-couchbase)** rather than in Github issues. 6 | 7 | # 1. Is This A Duplicate? 8 | 9 | It's great if you can scan the open issues to see if your problem/idea has been reported already. If so, feel free to add any new details or just a note that you hit this too. But if you're in a hurry, go ahead and skip this step -- we'd rather get duplicate reports than miss an issue! 10 | 11 | # 2. Describe The Bug 12 | 13 | ## Version 14 | 15 | Please indicate **what version of the software** you're using. If you compiled it yourself from source, it helps if you give the Git commit ID, or at least the branch name and date ("I last pulled from master on 6/30.") 16 | 17 | If the bug involves replication, also indicate what software and version is on the other end of the line, i.e. "Couchbase Lite Android 1.0" or "Sync Gateway 1.0" or "Sync Gateway commit f3d3229c" or "CouchDB 1.6". 18 | 19 | ## Include Steps To Reproduce 20 | 21 | The most **important information** to provide with a bug report is a clear set of steps to reproduce the problem. Include as much information as possible that you think may be related to the bug. An example would be: 22 | 23 | * Install app on ios6 device 24 | * Login with facebook 25 | * Turn off wifi 26 | * Add a new document 27 | * Turn on wifi 28 | * Saw no new documents on Sync Gateway (expected: there should have been some documents) 29 | 30 | ## Include Actual vs. Expected 31 | 32 | As mentioned above, the last thing in your steps to reproduce is the "actual vs expected" behavior. The reason this is important is because you may have a gross misunderstanding on what is supposed to happen. If you give a clear description of what actually happened as well as what you were expecting to happen, it will make the bug a lot easier to figure out. 33 | 34 | ## General Formatting 35 | 36 | Please **format source code or program output (including logs or backtraces) as code**. This makes it easier to read and prevents Github from interpreting any of it as Markdown formatting or bug numbers. To do this, put a line of just three back-quotes ("```") before and after it. (For inline code snippets, just put a single back-quote before and after.) 37 | 38 | **If you need to post a block of code/output that is longer than 1/2 a page, please don't paste it into the bug report** -- it's annoying to scroll past. Instead, create a [gist](https://gist.github.com) (or something similar) and just post a link to it. 39 | 40 | ## Crashes / Exceptions 41 | 42 | If the bug causes a crash or an uncaught exception, include a crash log or backtrace. **Please don't add this as a screenshot of the IDE** if you have any alternative. (In Xcode, use the `bt` command in the debugger console to dump a backtrace that you can copy.) 43 | 44 | 45 | -------------------------------------------------------------------------------- /LICENSE.TXT: -------------------------------------------------------------------------------- 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 | This allows you to use Javascript in map/reduce views, as opposed to native Java code (the default behavior for Couchbase-Lite). 2 | 3 | To "activate" this, you will need to include this library and it's dependencies, and add the following code when you initialize Couchbase-Lite: 4 | 5 | ``` 6 | CBLView.setCompiler(new CBLJavaScriptViewCompiler()); 7 | ``` 8 | 9 | See [couchbase-lite-android-liteserv](https://github.com/couchbaselabs/couchbase-lite-android-liteserv) for an example where this is used. 10 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'maven' 3 | apply plugin: 'eclipse' 4 | 5 | sourceCompatibility = JavaVersion.VERSION_1_6 6 | targetCompatibility = JavaVersion.VERSION_1_6 7 | 8 | repositories { 9 | maven { url 'http://files.couchbase.com/maven2/' } 10 | mavenCentral() 11 | mavenLocal() 12 | } 13 | 14 | def buildJavascriptWithArtifacts = System.getProperty("buildJavascriptWithArtifacts") 15 | 16 | dependencies { 17 | 18 | testCompile group: 'junit', name: 'junit', version: '4.11' 19 | 20 | // as discovered by trial and error, the build will fail if "compile" is 21 | // used: Error: duplicate files during packaging of APK. I guess it is 22 | // being implicitly included by being in the libs folder, and then "double included" 23 | // because of a "compile" directive to explicitly include the jar. 24 | testCompile fileTree(dir: 'libs', include: 'td_collator_so.jar') 25 | 26 | compile 'org.mozilla:rhino:1.7R3' 27 | 28 | compile buildJavascriptWithArtifacts == null ? 29 | project(':libraries:couchbase-lite-java-core') : 30 | 'com.couchbase.lite:couchbase-lite-java-core:' + System.getenv("MAVEN_UPLOAD_VERSION") 31 | 32 | } 33 | 34 | task createMavenDirectory(type: Exec) { 35 | 36 | ext { 37 | uploadUser = System.getenv("MAVEN_UPLOAD_USERNAME") + ":" + System.getenv("MAVEN_UPLOAD_PASSWORD") 38 | mkcolPath = System.getenv("MAVEN_UPLOAD_REPO_URL") + "com/couchbase/lite/couchbase-lite-java-javascript/" + System.getenv("MAVEN_UPLOAD_VERSION") + "/" 39 | } 40 | commandLine "curl", "--user", uploadUser, "-X", "MKCOL", mkcolPath 41 | } 42 | 43 | // this hack is only needed for apache mod_dav based Maven repo's like file.couchbase.com. otherwise, skip it 44 | createMavenDirectory.onlyIf { System.getenv("MAVEN_UPLOAD_REPO_URL").contains("files") } 45 | 46 | task uploadArchivesWrapper(dependsOn: createMavenDirectory) << { 47 | uploadArchives.execute() 48 | } 49 | 50 | uploadArchives { 51 | repositories { 52 | mavenDeployer { 53 | repository(url: System.getenv("MAVEN_UPLOAD_REPO_URL")) { 54 | authentication(userName: System.getenv("MAVEN_UPLOAD_USERNAME"), password: System.getenv("MAVEN_UPLOAD_PASSWORD")) 55 | } 56 | pom.version = System.getenv("MAVEN_UPLOAD_VERSION") != null ? System.getenv("MAVEN_UPLOAD_VERSION") : '' 57 | pom.groupId = 'com.couchbase.lite' 58 | pom.artifactId = 'couchbase-lite-java-javascript' 59 | pom.project { 60 | name 'com.couchbase.lite:couchbase-lite-java-javascript' 61 | description 'This allows you to use Javascript in map/reduce views, as opposed to native Java code (the default behavior for Couchbase-Lite).' 62 | url 'http://developer.couchbase.com/mobile/' 63 | licenses { 64 | license { 65 | name 'Couchbase, Inc. Community Edition License Agreement' 66 | url 'https://www.couchbase.com/binaries/content/assets/website/legal/ce-license-agreement.pdf' 67 | distribution 'repo' 68 | } 69 | } 70 | scm { 71 | url 'http://developer.couchbase.com/mobile/' 72 | connection 'scm:git@github.com:couchbase/couchbase-lite-java-javascript.git' 73 | developerConnection 'scm:git@github.com:couchbase/couchbase-lite-java-javascript.git' 74 | } 75 | developers { 76 | developer { 77 | name 'Couchbase Mobile' 78 | email 'mobile@couchbase.com' 79 | organization 'Couchbase' 80 | organizationUrl 'http://www.couchbase.com' 81 | } 82 | } 83 | } 84 | } 85 | } 86 | } 87 | 88 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/couchbase/couchbase-lite-java-javascript/beba5ba1af669d7c9c6e04e18ab75052b33e9166/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Feb 06 16:23:51 PST 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://downloads.gradle.org/distributions/gradle-2.4-all.zip 7 | -------------------------------------------------------------------------------- /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 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /libs/td_collator_so.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/couchbase/couchbase-lite-java-javascript/beba5ba1af669d7c9c6e04e18ab75052b33e9166/libs/td_collator_so.jar -------------------------------------------------------------------------------- /release/upload_android_artifacts.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | : ${MAVEN_UPLOAD_VERSION:?"Need to set 'MAVEN_UPLOAD_VERSION' non-empty"} 3 | : ${MAVEN_UPLOAD_USERNAME:?"Need to set MAVEN_UPLOAD_USERNAME non-empty"} 4 | : ${MAVEN_UPLOAD_PASSWORD:?"Need to set MAVEN_UPLOAD_PASSWORD non-empty"} 5 | : ${MAVEN_UPLOAD_REPO_URL:?"Need to set MAVEN_UPLOAD_REPO_URL non-empty"} 6 | 7 | #at first build all projects 8 | ./gradlew :libraries:couchbase-lite-java-core:build && ./gradlew assemble 9 | #&& ./gradlew :build -DbuildJavascriptWithArtifacts && 10 | #then upload artifacts 11 | ./gradlew :uploadArchivesWrapper -DbuildJavascriptWithArtifacts 12 | -------------------------------------------------------------------------------- /settings.gradle.example: -------------------------------------------------------------------------------- 1 | include ':couchbase-lite-java-javascript', ':libraries:couchbase-lite-java-core' -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/JavaScriptReplicationFilterCompiler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015 Couchbase, Inc All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | * either express or implied. See the License for the specific language governing permissions 12 | * and limitations under the License. 13 | */ 14 | 15 | package com.couchbase.lite.javascript; 16 | 17 | import com.couchbase.lite.ReplicationFilter; 18 | import com.couchbase.lite.ReplicationFilterCompiler; 19 | 20 | /** 21 | * Created by hideki on 10/28/15. 22 | */ 23 | public class JavaScriptReplicationFilterCompiler implements ReplicationFilterCompiler { 24 | @Override 25 | public ReplicationFilter compileFilterFunction(String source, String language) { 26 | if (language != null && language.equalsIgnoreCase("javascript")) { 27 | return new ReplicationFilterBlockRhino(source); 28 | } 29 | throw new IllegalArgumentException(language + " is not supported"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/JavaScriptViewCompiler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015 Couchbase, Inc All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | * either express or implied. See the License for the specific language governing permissions 12 | * and limitations under the License. 13 | */ 14 | package com.couchbase.lite.javascript; 15 | 16 | import com.couchbase.lite.Mapper; 17 | import com.couchbase.lite.Reducer; 18 | import com.couchbase.lite.ViewCompiler; 19 | 20 | public class JavaScriptViewCompiler implements ViewCompiler { 21 | @Override 22 | public Mapper compileMap(String source, String language) { 23 | if (language != null && language.equalsIgnoreCase("javascript")) { 24 | return new ViewMapBlockRhino(source); 25 | } 26 | throw new IllegalArgumentException(language + " is not supported"); 27 | } 28 | 29 | @Override 30 | public Reducer compileReduce(String source, String language) { 31 | if (language != null && language.equalsIgnoreCase("javascript")) { 32 | return new ViewReduceBlockRhino(source); 33 | } 34 | throw new IllegalArgumentException(language + " is not supported"); 35 | } 36 | } 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/ReplicationFilterBlockRhino.java: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Couchbase, Inc. All rights reserved. 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | // except in compliance with the License. You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software distributed under the 10 | // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | // either express or implied. See the License for the specific language governing permissions 12 | // and limitations under the License. 13 | // 14 | package com.couchbase.lite.javascript; 15 | 16 | import com.couchbase.lite.ReplicationFilter; 17 | import com.couchbase.lite.SavedRevision; 18 | import com.couchbase.lite.javascript.scopes.GlobalScope; 19 | import com.couchbase.lite.javascript.wrapper.CustomWrapFactory; 20 | import com.couchbase.lite.util.Log; 21 | 22 | import org.mozilla.javascript.Function; 23 | import org.mozilla.javascript.Scriptable; 24 | import org.mozilla.javascript.WrapFactory; 25 | 26 | import java.util.Map; 27 | 28 | /** 29 | * Created by hideki on 10/28/15. 30 | */ 31 | public class ReplicationFilterBlockRhino implements ReplicationFilter { 32 | public static String TAG = "JavaScriptEngine"; 33 | 34 | private static WrapFactory wrapFactory = new CustomWrapFactory(); 35 | private Scriptable scope; 36 | private GlobalScope globalScope; 37 | private Function filterFunction; 38 | 39 | // NOTE: Scope is sharable with multiple threads, it seems `Function` is not. 40 | // Compiling javascript codes for every request makes slow. 41 | // It is reason current code base re-use compiled Function. 42 | // Instead of compiling for every request, use `synchronized` to protect Function 43 | // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scopes_and_Contexts 44 | private final Object lockFunction = new Object(); 45 | 46 | public ReplicationFilterBlockRhino(String src) { 47 | org.mozilla.javascript.Context ctx = org.mozilla.javascript.Context.enter(); 48 | try { 49 | ctx.setOptimizationLevel(-1); 50 | ctx.setWrapFactory(wrapFactory); 51 | globalScope = new GlobalScope(); 52 | scope = ctx.initStandardObjects(globalScope, true); 53 | filterFunction = ctx.compileFunction(scope, src, "filter", 0, null); 54 | } finally { 55 | org.mozilla.javascript.Context.exit(); 56 | } 57 | } 58 | 59 | @Override 60 | public boolean filter(SavedRevision revision, Map params) { 61 | org.mozilla.javascript.Context ctx = org.mozilla.javascript.Context.enter(); 62 | try { 63 | ctx.setOptimizationLevel(-1); 64 | ctx.setWrapFactory(wrapFactory); 65 | Scriptable localScope = ctx.newObject(scope); 66 | localScope.setPrototype(scope); 67 | localScope.setParentScope(null); 68 | Object jsDocument = org.mozilla.javascript.Context.javaToJS(revision.getProperties(), localScope); 69 | Object jsParams = org.mozilla.javascript.Context.javaToJS(params, localScope); 70 | 71 | try { 72 | synchronized (lockFunction) { 73 | Object result = filterFunction.call(ctx, localScope, null, new Object[]{jsDocument, jsParams}); 74 | return ((Boolean) result).booleanValue(); 75 | } 76 | } catch (org.mozilla.javascript.RhinoException e) { 77 | Log.e(TAG, "Error in filterFunction.call()", e); 78 | return false; 79 | } 80 | } finally { 81 | org.mozilla.javascript.Context.exit(); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/ViewMapBlockRhino.java: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Couchbase, Inc. All rights reserved. 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | // except in compliance with the License. You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software distributed under the 10 | // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | // either express or implied. See the License for the specific language governing permissions 12 | // and limitations under the License. 13 | // 14 | package com.couchbase.lite.javascript; 15 | 16 | import com.couchbase.lite.Emitter; 17 | import com.couchbase.lite.Mapper; 18 | import com.couchbase.lite.javascript.scopes.MapGlobalScope; 19 | import com.couchbase.lite.javascript.wrapper.CustomWrapFactory; 20 | import com.couchbase.lite.util.Log; 21 | 22 | import org.mozilla.javascript.Function; 23 | import org.mozilla.javascript.Scriptable; 24 | import org.mozilla.javascript.WrapFactory; 25 | 26 | import java.util.Map; 27 | 28 | class ViewMapBlockRhino implements Mapper { 29 | private final static String TAG = "JavaScriptEngine"; 30 | 31 | private static WrapFactory wrapFactory = new CustomWrapFactory(); 32 | private Scriptable globalScope; 33 | private MapGlobalScope mapGlobalScope; 34 | private Function mapFunction; 35 | 36 | // NOTE: Scope is sharable with multiple threads, it seems `Function` is not. 37 | // Compiling javascript codes for every request makes slow. 38 | // It is reason current code base re-use compiled Function. 39 | // Instead of compiling for every request, use `synchronized` to protect Function 40 | // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scopes_and_Contexts 41 | private final Object lockFunction = new Object(); 42 | 43 | public ViewMapBlockRhino(String src) { 44 | org.mozilla.javascript.Context ctx = org.mozilla.javascript.Context.enter(); 45 | try { 46 | ctx.setOptimizationLevel(-1); 47 | ctx.setWrapFactory(wrapFactory); 48 | mapGlobalScope = new MapGlobalScope(); 49 | globalScope = ctx.initStandardObjects(mapGlobalScope, true); 50 | mapFunction = ctx.compileFunction(globalScope, src, "map", 0, null); 51 | } finally { 52 | org.mozilla.javascript.Context.exit(); 53 | } 54 | } 55 | 56 | @Override 57 | public void map(Map document, Emitter emitter) { 58 | mapGlobalScope.setEmitter(emitter); 59 | 60 | org.mozilla.javascript.Context ctx = org.mozilla.javascript.Context.enter(); 61 | try { 62 | ctx.setOptimizationLevel(-1); 63 | ctx.setWrapFactory(wrapFactory); 64 | 65 | Scriptable localScope = ctx.newObject(globalScope); 66 | localScope.setPrototype(globalScope); 67 | localScope.setParentScope(null); 68 | 69 | Object jsDocument = org.mozilla.javascript.Context.javaToJS(document, localScope); 70 | 71 | try { 72 | synchronized (lockFunction) { 73 | mapFunction.call(ctx, localScope, null, new Object[]{jsDocument}); 74 | } 75 | } catch (org.mozilla.javascript.RhinoException e) { 76 | Log.e(TAG, "Error in calling JavaScript map function", e); 77 | return; 78 | } 79 | } finally { 80 | org.mozilla.javascript.Context.exit(); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/ViewReduceBlockRhino.java: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Couchbase, Inc. All rights reserved. 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | // except in compliance with the License. You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software distributed under the 10 | // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | // either express or implied. See the License for the specific language governing permissions 12 | // and limitations under the License. 13 | // 14 | package com.couchbase.lite.javascript; 15 | 16 | import com.couchbase.lite.Reducer; 17 | import com.couchbase.lite.javascript.scopes.ReduceGlobalScope; 18 | import com.couchbase.lite.javascript.wrapper.CustomWrapFactory; 19 | import com.couchbase.lite.util.Log; 20 | 21 | import org.mozilla.javascript.Function; 22 | import org.mozilla.javascript.Scriptable; 23 | import org.mozilla.javascript.ScriptableObject; 24 | import org.mozilla.javascript.WrapFactory; 25 | 26 | import java.util.List; 27 | 28 | class ViewReduceBlockRhino implements Reducer { 29 | private final static String TAG = "JavaScriptEngine"; 30 | 31 | private static WrapFactory wrapFactory = new CustomWrapFactory(); 32 | private final ReduceGlobalScope reduceGlobalScope; 33 | private final ScriptableObject globalScope; 34 | private final Function reduceFunction; 35 | private final NativReduceFunctions nativeReduce; 36 | 37 | // NOTE: Scope is sharable with multiple threads, it seems `Function` is not. 38 | // Compiling javascript codes for every request makes slow. 39 | // It is reason current code base re-use compiled Function. 40 | // Instead of compiling for every request, use `synchronized` to protect Function 41 | // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scopes_and_Contexts 42 | private final Object lockFunction = new Object(); 43 | 44 | public ViewReduceBlockRhino(String src) { 45 | 46 | nativeReduce = NativReduceFunctions.fromKey(src); 47 | 48 | if (nativeReduce == NativReduceFunctions.DEFAULT) { 49 | org.mozilla.javascript.Context ctx = org.mozilla.javascript.Context.enter(); 50 | try { 51 | ctx.setOptimizationLevel(-1); 52 | ctx.setWrapFactory(wrapFactory); 53 | reduceGlobalScope = new ReduceGlobalScope(); 54 | globalScope = ctx.initStandardObjects(reduceGlobalScope, true); 55 | reduceFunction = ctx.compileFunction(globalScope, src, "reduce", 0, null); 56 | } finally { 57 | org.mozilla.javascript.Context.exit(); 58 | } 59 | } else { 60 | // not needed if no JS is executed 61 | reduceGlobalScope = null; 62 | globalScope = null; 63 | reduceFunction = null; 64 | } 65 | } 66 | 67 | @Override 68 | public Object reduce(List keys, List values, boolean reReduce) { 69 | switch (nativeReduce) { 70 | case SUM: 71 | return nativeSum(keys, values, reReduce); 72 | case COUNT: 73 | return nativeCount(keys, values, reReduce); 74 | case DEFAULT: 75 | default: 76 | org.mozilla.javascript.Context ctx = org.mozilla.javascript.Context.enter(); 77 | try { 78 | ctx.setOptimizationLevel(-1); 79 | ctx.setWrapFactory(wrapFactory); 80 | 81 | Scriptable localScope = ctx.newObject(globalScope); 82 | localScope.setPrototype(globalScope); 83 | localScope.setParentScope(null); 84 | 85 | Object[] args = new Object[3]; 86 | args[0] = org.mozilla.javascript.Context.javaToJS(keys, localScope); 87 | args[1] = org.mozilla.javascript.Context.javaToJS(values, localScope); 88 | args[2] = org.mozilla.javascript.Context.javaToJS(reReduce, localScope); 89 | 90 | try { 91 | synchronized (lockFunction) { 92 | return reduceFunction.call(ctx, localScope, null, args); 93 | } 94 | } catch (org.mozilla.javascript.RhinoException e) { 95 | Log.e(TAG, "Error in calling JavaScript reduce function", e); 96 | return null; 97 | } 98 | } finally { 99 | org.mozilla.javascript.Context.exit(); 100 | } 101 | } 102 | } 103 | 104 | // rhino numbers are double, so we return double not int 105 | private static double nativeSum(List keys, List values, boolean reReduce) { 106 | 107 | double sum = 0; 108 | int length = values.size(); 109 | for (int i = 0; i < length; i++) { 110 | sum = sum + new Double(String.valueOf(values.get(i))); 111 | } 112 | return sum; 113 | } 114 | 115 | // rhino numbers are double, so we return double not int 116 | private static double nativeCount(List keys, List values, boolean reReduce) { 117 | if (reReduce) { 118 | return nativeSum(keys, values, reReduce); 119 | } else { 120 | return new Double(values.size()); 121 | } 122 | } 123 | 124 | enum NativReduceFunctions { 125 | // TODO add _stats 126 | COUNT("_count"), SUM("_sum"), DEFAULT("default"); 127 | private String mKey; 128 | 129 | private NativReduceFunctions(String key) { 130 | mKey = key; 131 | } 132 | 133 | public static NativReduceFunctions fromKey(String key) { 134 | if (key != null) { 135 | for (NativReduceFunctions type : values()) { 136 | if (key.equalsIgnoreCase(type.mKey)) { 137 | return type; 138 | } 139 | } 140 | } 141 | return DEFAULT; 142 | } 143 | 144 | public String getKey() { 145 | return mKey; 146 | } 147 | 148 | @Override 149 | public String toString() { 150 | return mKey; 151 | } 152 | } 153 | } -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/scopes/GlobalScope.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015 Couchbase, Inc All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | * either express or implied. See the License for the specific language governing permissions 12 | * and limitations under the License. 13 | */ 14 | package com.couchbase.lite.javascript.scopes; 15 | 16 | import com.couchbase.lite.util.Log; 17 | 18 | import org.mozilla.javascript.ScriptableObject; 19 | 20 | public class GlobalScope extends ScriptableObject { 21 | public GlobalScope() { 22 | super(); 23 | String[] names = {"log"}; 24 | this.defineFunctionProperties(names, GlobalScope.class, ScriptableObject.DONTENUM); 25 | } 26 | 27 | public static void log(Object msg) { 28 | // right tag? 29 | // TODO maybe more sophisticated string conversion 30 | Log.d(Log.TAG_VIEW, msg.toString()); 31 | } 32 | 33 | @Override 34 | public String getClassName() { 35 | return "global"; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/scopes/MapGlobalScope.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015 Couchbase, Inc All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | * either express or implied. See the License for the specific language governing permissions 12 | * and limitations under the License. 13 | */ 14 | package com.couchbase.lite.javascript.scopes; 15 | 16 | import com.couchbase.lite.Emitter; 17 | 18 | import org.mozilla.javascript.ScriptableObject; 19 | 20 | public class MapGlobalScope extends GlobalScope { 21 | private Emitter emitter; 22 | 23 | public MapGlobalScope() { 24 | super(); 25 | String[] names = {"emit"}; 26 | this.defineFunctionProperties(names, MapGlobalScope.class, ScriptableObject.DONTENUM); 27 | } 28 | 29 | public void setEmitter(Emitter emitter) { 30 | this.emitter = emitter; 31 | } 32 | 33 | // emit might fail when called in a method of a JS Object 34 | // I don't think that is an issue - who will create a Object in a view? 35 | // solution would be to make it static and get the emitter from the "thisObj" 36 | // see Rhino FunctionObject documentation (keyword varargs, "second form") 37 | 38 | public void emit(Object key, Object value) { 39 | emitter.emit(key, value); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/scopes/ReduceGlobalScope.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015 Couchbase, Inc All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | * either express or implied. See the License for the specific language governing permissions 12 | * and limitations under the License. 13 | */ 14 | package com.couchbase.lite.javascript.scopes; 15 | 16 | import com.couchbase.lite.CouchbaseLiteException; 17 | import com.couchbase.lite.Status; 18 | 19 | import org.mozilla.javascript.NativeArray; 20 | import org.mozilla.javascript.ScriptableObject; 21 | import org.mozilla.javascript.Wrapper; 22 | 23 | /** 24 | * Created by stefan on 10.05.15. 25 | */ 26 | public class ReduceGlobalScope extends GlobalScope { 27 | 28 | public ReduceGlobalScope() { 29 | super(); 30 | String[] names = {"sum"}; 31 | this.defineFunctionProperties(names, ReduceGlobalScope.class, ScriptableObject.DONTENUM); 32 | } 33 | 34 | // rhino numbers are double, so we return double 35 | public static double sum(Object o) throws CouchbaseLiteException { 36 | if (o instanceof Wrapper) { 37 | o = ((Wrapper) o).unwrap(); 38 | } 39 | if (o instanceof NativeArray) { 40 | o = ((NativeArray) o).toArray(); 41 | } 42 | 43 | if (o.getClass().isArray()) { 44 | Object[] arr = (Object[]) o; 45 | double sum = 0; 46 | for (int i = 0; i < arr.length; i++) { 47 | sum = sum + Double.valueOf(String.valueOf(arr[i])); 48 | } 49 | return sum; 50 | } 51 | 52 | throw new CouchbaseLiteException("don't know how to sum" + o.toString(), new Status()); 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/couchbase/lite/javascript/wrapper/CustomWrapFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015 Couchbase, Inc All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | * either express or implied. See the License for the specific language governing permissions 12 | * and limitations under the License. 13 | */ 14 | package com.couchbase.lite.javascript.wrapper; 15 | 16 | import org.mozilla.javascript.Context; 17 | import org.mozilla.javascript.NativeArray; 18 | import org.mozilla.javascript.NativeObject; 19 | import org.mozilla.javascript.Scriptable; 20 | import org.mozilla.javascript.ScriptableObject; 21 | import org.mozilla.javascript.WrapFactory; 22 | 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | public class CustomWrapFactory extends WrapFactory { 27 | 28 | public CustomWrapFactory() { 29 | setJavaPrimitiveWrap(false); 30 | } 31 | 32 | @Override 33 | public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class staticType) { 34 | 35 | if (javaObject instanceof Map) { 36 | 37 | NativeObject nativeObject = new NativeObject(); 38 | 39 | nativeObject.setPrototype(ScriptableObject.getClassPrototype(scope, "Object")); 40 | 41 | Map map = (Map) javaObject; 42 | for (Map.Entry entry : map.entrySet()) { 43 | nativeObject.defineProperty(entry.getKey(), wrap(cx, scope, entry.getValue(), staticType), NativeObject.READONLY); 44 | } 45 | return nativeObject; 46 | } else if (javaObject instanceof List) { 47 | List list = (List) javaObject; 48 | 49 | Object[] newArr = new Object[list.size()]; 50 | 51 | for (int i = 0; i < list.size(); i++) { 52 | newArr[i] = wrap(cx, scope, list.get(i), staticType); 53 | } 54 | 55 | NativeArray na = new NativeArray(newArr); 56 | na.setPrototype(ScriptableObject.getClassPrototype(scope, "Array")); 57 | return na; 58 | } 59 | 60 | return super.wrapAsJavaObject(cx, scope, javaObject, staticType); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/couchbase/couchbase-lite-java-javascript/beba5ba1af669d7c9c6e04e18ab75052b33e9166/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/couchbase/couchbase-lite-java-javascript/beba5ba1af669d7c9c6e04e18ab75052b33e9166/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/couchbase/couchbase-lite-java-javascript/beba5ba1af669d7c9c6e04e18ab75052b33e9166/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/main/res/values-v11/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/res/values-v14/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | CBLiteJavascript 3 | 4 | -------------------------------------------------------------------------------- /src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 14 | 15 | 16 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/test/assets/test.properties: -------------------------------------------------------------------------------- 1 | # if you want to change these settings 2 | # copy this file to "local-test.properties" in the same directory 3 | # values in that file will override these 4 | # and it will be ignored by git automatically 5 | replicationProtocol=http 6 | replicationServer=10.0.2.2 7 | replicationPort=4984 8 | replicationDatabase=database 9 | replicationAdminUser= 10 | replicationAdminPassword= -------------------------------------------------------------------------------- /src/test/java/com/couchbase/lite/ReplicationFilterTestCase.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015 Couchbase, Inc All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 11 | * either express or implied. See the License for the specific language governing permissions 12 | * and limitations under the License. 13 | */ 14 | 15 | package com.couchbase.lite; 16 | 17 | import com.couchbase.lite.internal.RevisionInternal; 18 | import com.couchbase.lite.javascript.JavaScriptReplicationFilterCompiler; 19 | 20 | import junit.framework.TestCase; 21 | 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | /** 26 | * Created by hideki on 11/9/15. 27 | */ 28 | public class ReplicationFilterTestCase extends TestCase { 29 | private JavaScriptReplicationFilterCompiler replicationFilterCompiler; 30 | 31 | @Override 32 | public void setUp() throws Exception { 33 | super.setUp(); 34 | replicationFilterCompiler = new JavaScriptReplicationFilterCompiler(); 35 | } 36 | 37 | public void testSimpleFilterTrue() { 38 | Map props = new HashMap(); 39 | props.put("_id", "foo"); 40 | props.put("_rev", "1-1111"); 41 | props.put("_deleted", false); 42 | props.put("type", "order"); 43 | props.put("SeatNumber", 10); 44 | RevisionInternal revisionInternal = new RevisionInternal(props); 45 | SavedRevision savedRevision = new SavedRevision((Document)null, revisionInternal); 46 | ReplicationFilter replicationFilter = replicationFilterCompiler.compileFilterFunction("function(doc, req) {if(doc.type && doc.type == 'order') {return true;}else{return false}}", "javascript"); 47 | assertTrue(replicationFilter.filter(savedRevision, null)); 48 | } 49 | 50 | public void testSimpleFilterFalse() { 51 | Map props = new HashMap(); 52 | props.put("_id", "foo"); 53 | props.put("_rev", "1-1111"); 54 | props.put("_deleted", false); 55 | props.put("type", "user"); 56 | props.put("Name", "tom"); 57 | RevisionInternal revisionInternal = new RevisionInternal(props); 58 | SavedRevision savedRevision = new SavedRevision((Document)null, revisionInternal); 59 | ReplicationFilter replicationFilter = replicationFilterCompiler.compileFilterFunction("function(doc, req) {if(doc.type && doc.type == 'order') {return true;}else{return false}}", "javascript"); 60 | assertFalse(replicationFilter.filter(savedRevision, null)); 61 | } 62 | 63 | 64 | public void testSimpleFilterWithReqTrue() { 65 | Map props = new HashMap(); 66 | props.put("_id", "foo"); 67 | props.put("_rev", "1-1111"); 68 | props.put("_deleted", false); 69 | props.put("type", "order"); 70 | props.put("SeatNumber", 10); 71 | RevisionInternal revisionInternal = new RevisionInternal(props); 72 | SavedRevision savedRevision = new SavedRevision((Document)null, revisionInternal); 73 | ReplicationFilter replicationFilter = replicationFilterCompiler.compileFilterFunction("function(doc, req) {if(doc.type && doc.type == 'order' && req.abc == 1) {return true;}else{return false}}", "javascript"); 74 | Map req = new HashMap(); 75 | req.put("abc", 1); 76 | assertTrue(replicationFilter.filter(savedRevision, req)); 77 | } 78 | 79 | public void testSimpleFilterWithReqFalse() { 80 | Map props = new HashMap(); 81 | props.put("_id", "foo"); 82 | props.put("_rev", "1-1111"); 83 | props.put("_deleted", false); 84 | props.put("type", "user"); 85 | props.put("Name", "tom"); 86 | RevisionInternal revisionInternal = new RevisionInternal(props); 87 | SavedRevision savedRevision = new SavedRevision((Document)null, revisionInternal); 88 | ReplicationFilter replicationFilter = replicationFilterCompiler.compileFilterFunction("function(doc, req) {if(doc.type && doc.type == 'order' && req.abc == 1) {return true;}else{return false}}", "javascript"); 89 | Map req = new HashMap(); 90 | req.put("abc", 2); 91 | assertFalse(replicationFilter.filter(savedRevision, req)); 92 | } 93 | public void testSimpleFilterWithReqFalse2() { 94 | Map props = new HashMap(); 95 | props.put("_id", "foo"); 96 | props.put("_rev", "1-1111"); 97 | props.put("_deleted", false); 98 | props.put("type", "user"); 99 | props.put("Name", "tom"); 100 | RevisionInternal revisionInternal = new RevisionInternal(props); 101 | SavedRevision savedRevision = new SavedRevision((Document)null, revisionInternal); 102 | ReplicationFilter replicationFilter = replicationFilterCompiler.compileFilterFunction("function(doc, req) {if(doc.type && doc.type == 'order' && req.abc == 1) {return true;}else{return false}}", "javascript"); 103 | assertFalse(replicationFilter.filter(savedRevision, null)); 104 | } 105 | public void testInvalidLanguage() { 106 | try { 107 | ReplicationFilter replicationFilter = replicationFilterCompiler.compileFilterFunction("function(doc, req) {if(doc.type && doc.type == 'order' && req.abc == 1) {return true;}else{return false}}", "C++"); 108 | fail("IllegalArgumentException should be thrown"); 109 | } 110 | catch (IllegalArgumentException e){ 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/test/java/com/couchbase/lite/javascript/JavaScriptTestCase.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.lite.javascript; 2 | 3 | import com.couchbase.lite.Mapper; 4 | import com.couchbase.lite.Reducer; 5 | import com.couchbase.lite.javascript.helper.EmitPair; 6 | import com.couchbase.lite.javascript.helper.MockEmiter; 7 | 8 | import junit.framework.TestCase; 9 | 10 | import java.util.ArrayList; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | /** 16 | * Created by stefan on 16.05.15. 17 | */ 18 | public class JavaScriptTestCase extends TestCase { 19 | 20 | private JavaScriptViewCompiler viewCompiler; 21 | private MockEmiter emiter; 22 | 23 | @Override 24 | public void setUp() throws Exception { 25 | super.setUp(); 26 | 27 | viewCompiler = new JavaScriptViewCompiler(); 28 | emiter = new MockEmiter(); 29 | } 30 | 31 | public void testSimpleJavaScriptView() { 32 | Map doc = new HashMap(); 33 | doc.put("_id", "foo"); 34 | 35 | Mapper map = viewCompiler.compileMap("function(doc){emit(doc._id,null);}", "javascript"); 36 | 37 | map.map(doc, emiter); 38 | 39 | assertEquals(1, emiter.count()); 40 | assertEquals(new EmitPair("foo", null), emiter.get(0)); 41 | } 42 | 43 | public void testReduceSum() { 44 | List keys = new ArrayList(5); 45 | List values = new ArrayList(5); 46 | 47 | values.add(0, 1); 48 | values.add(1, 2); 49 | values.add(2, 3); 50 | values.add(3, 4); 51 | values.add(4, 5); 52 | 53 | Reducer reduce = viewCompiler.compileReduce("function(keys, values, rereduce){return sum(values)}", "javascript"); 54 | 55 | Object result = reduce.reduce(keys, values, false); 56 | 57 | assertEquals(new Double(15), result); 58 | } 59 | 60 | public void testReduceNativeSum() { 61 | List keys = new ArrayList(5); 62 | List values = new ArrayList(5); 63 | 64 | values.add(0, 1); 65 | values.add(1, 2); 66 | values.add(2, 3); 67 | values.add(3, 4); 68 | values.add(4, 5); 69 | 70 | Reducer reduce = viewCompiler.compileReduce("_sum", "javascript"); 71 | 72 | Object result = reduce.reduce(keys, values, false); 73 | 74 | assertEquals(new Double(15), result); 75 | } 76 | 77 | public void testReduceCount() { 78 | List keys = new ArrayList(5); 79 | List values = new ArrayList(5); 80 | 81 | values.add(0, 1); 82 | values.add(1, 2); 83 | values.add(2, 3); 84 | values.add(3, 4); 85 | values.add(4, 5); 86 | 87 | Reducer reduce = viewCompiler.compileReduce("function(keys, values, rereduce){ if (rereduce) { return sum(values); } else { return values.length; }}", "javascript"); 88 | 89 | Object result = reduce.reduce(keys, values, false); 90 | assertEquals(new Double(5), result); 91 | 92 | // re-reduce 93 | result = reduce.reduce(keys, values, true); 94 | assertEquals(new Double(15), result); 95 | } 96 | 97 | public void testReduceKeysAndValuesAreArrays() { 98 | 99 | List keys = new ArrayList(0); 100 | List values = new ArrayList(0); 101 | 102 | Reducer reduce = viewCompiler.compileReduce("function(keys, values, rereduce){ return (Array.isArray(keys) && Array.isArray(values)) }", "javascript"); 103 | 104 | Object result = reduce.reduce(keys, values, false); 105 | assertEquals(true, result); 106 | } 107 | 108 | public void testReduceNativeCount() { 109 | List keys = new ArrayList(5); 110 | List values = new ArrayList(5); 111 | 112 | values.add(0, 1); 113 | values.add(1, 2); 114 | values.add(2, 3); 115 | values.add(3, 4); 116 | values.add(4, 5); 117 | 118 | Reducer reduce = viewCompiler.compileReduce("_count", "javascript"); 119 | 120 | Object result = reduce.reduce(keys, values, false); 121 | assertEquals(new Double(5), result); 122 | 123 | // re-reduce 124 | result = reduce.reduce(keys, values, true); 125 | assertEquals(new Double(15), result); 126 | } 127 | 128 | public void testScopeSeparation() { 129 | Map doc = new HashMap(); 130 | doc.put("_id", "foo"); 131 | 132 | // try to put a var "x" into global scope 133 | Mapper map = viewCompiler.compileMap("function(doc){var x = x || 0; emit(x++,null);}", "javascript"); 134 | 135 | map.map(doc, emiter); 136 | map.map(doc, emiter); 137 | map.map(doc, emiter); 138 | 139 | assertEquals(3, emiter.count()); 140 | assertEquals(new EmitPair(0.0, null), emiter.get(0)); 141 | assertEquals(new EmitPair(0.0, null), emiter.get(1)); 142 | assertEquals(new EmitPair(0.0, null), emiter.get(2)); 143 | } 144 | 145 | public void testJavaScriptDesignDocument() { 146 | Map doc1 = new HashMap(); 147 | doc1.put("_id", "doc1"); 148 | doc1.put("message", "hello"); 149 | Map doc2 = new HashMap(); 150 | doc2.put("_id", "doc2"); 151 | doc2.put("message", "guten tag"); 152 | Map doc3 = new HashMap(); 153 | doc3.put("_id", "doc3"); 154 | doc3.put("message", "bonjour"); 155 | 156 | Mapper map = viewCompiler.compileMap("function(doc) { if(doc.message) { emit(doc.message, 1); } }", "javascript"); 157 | 158 | map.map(doc1, emiter); 159 | map.map(doc2, emiter); 160 | map.map(doc3, emiter); 161 | 162 | assertEquals(3, emiter.count()); 163 | assertEquals(new EmitPair("hello", 1.0), emiter.get(0)); 164 | assertEquals(new EmitPair("guten tag", 1.0), emiter.get(1)); 165 | assertEquals(new EmitPair("bonjour", 1.0), emiter.get(2)); 166 | } 167 | 168 | public void testRealJavaScriptDesignDocument() { 169 | Map doc1 = new HashMap(); 170 | doc1.put("_id", "doc1"); 171 | List cat1 = new ArrayList(); 172 | cat1.add("apple"); 173 | cat1.add("bannana"); 174 | doc1.put("categories", cat1); 175 | 176 | Map doc2 = new HashMap(); 177 | doc2.put("_id", "doc2"); 178 | List cat2 = new ArrayList(); 179 | cat2.add("clock"); 180 | cat2.add("dill"); 181 | doc2.put("categories", cat2); 182 | 183 | Map doc3 = new HashMap(); 184 | doc3.put("_id", "doc3"); 185 | List cat3 = new ArrayList(); 186 | cat3.add("elephant"); 187 | cat3.add("fun"); 188 | cat3.add("apple"); 189 | doc3.put("categories", cat3); 190 | 191 | Mapper map = viewCompiler.compileMap("function(doc) { if (doc.categories) { for (i in doc.categories) { emit(doc.categories[i], 1); } } }", "javascript"); 192 | 193 | map.map(doc1, emiter); 194 | map.map(doc2, emiter); 195 | map.map(doc3, emiter); 196 | 197 | assertEquals(7, emiter.count()); 198 | assertEquals(new EmitPair("apple", 1.0), emiter.get(0)); 199 | assertEquals(new EmitPair("bannana", 1.0), emiter.get(1)); 200 | assertEquals(new EmitPair("clock", 1.0), emiter.get(2)); 201 | assertEquals(new EmitPair("dill", 1.0), emiter.get(3)); 202 | assertEquals(new EmitPair("elephant", 1.0), emiter.get(4)); 203 | assertEquals(new EmitPair("fun", 1.0), emiter.get(5)); 204 | assertEquals(new EmitPair("apple", 1.0), emiter.get(6)); 205 | } 206 | 207 | public void testJavaScriptDesignDocumentThatDealsWithArrays() { 208 | Map doc1 = new HashMap(); 209 | doc1.put("_id", "doc1"); 210 | List producers1 = new ArrayList(); 211 | producers1.add("abc"); 212 | doc1.put("producers", producers1); 213 | doc1.put("collection", "product"); 214 | 215 | Mapper map = viewCompiler.compileMap("function(doc) { if ('product' === doc.collection && doc.producers) { doc.producers.forEach(function(each) { emit(each, doc); }); } }", "javascript"); 216 | 217 | map.map(doc1, emiter); 218 | 219 | assertEquals(1, emiter.count()); 220 | assertEquals(new EmitPair("abc", doc1), emiter.get(0)); 221 | } 222 | 223 | public void testShouldLeaveOutDocumentsWhenMapBlockThrowsAnException() { 224 | Map doc1 = new HashMap(); 225 | doc1.put("_id", "good"); 226 | Map doc2 = new HashMap(); 227 | doc2.put("_id", "bad"); 228 | 229 | Mapper map = viewCompiler.compileMap("function(doc) { if (doc._id === 'bad') throw new Error('gotcha!'); emit(1, doc); }", "javascript"); 230 | 231 | map.map(doc1, emiter); 232 | map.map(doc2, emiter); 233 | 234 | assertEquals(1, emiter.count()); 235 | assertEquals(new EmitPair(1.0, doc1), emiter.get(0)); 236 | } 237 | 238 | public void testShouldReturnEmptyViewIfJavaScriptIsErranous() { 239 | Map doc1 = new HashMap(); 240 | doc1.put("_id", "good"); 241 | 242 | Mapper map = viewCompiler.compileMap("function(doc) { }", "javascript"); 243 | 244 | map.map(doc1, emiter); 245 | 246 | assertEquals(0, emiter.count()); 247 | } 248 | } 249 | -------------------------------------------------------------------------------- /src/test/java/com/couchbase/lite/javascript/PerformanceTestCase.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.lite.javascript; 2 | 3 | import com.couchbase.lite.Emitter; 4 | import com.couchbase.lite.Mapper; 5 | import com.couchbase.lite.javascript.helper.MockEmiter; 6 | 7 | import junit.framework.TestCase; 8 | 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * Created by stefan on 16.05.15. 14 | */ 15 | 16 | /* 17 | NOT significant, Android devices behave different, GC can ruin everything. 18 | */ 19 | public class PerformanceTestCase extends TestCase { 20 | 21 | private JavaScriptViewCompiler viewCompiler; 22 | 23 | @Override 24 | public void setUp() throws Exception { 25 | super.setUp(); 26 | 27 | viewCompiler = new JavaScriptViewCompiler(); 28 | } 29 | 30 | public void test200SimpleJavaScriptView() { 31 | MockEmiter jsEmiter = new MockEmiter(); 32 | 33 | Map doc = new HashMap(); 34 | doc.put("_id", "foo"); 35 | 36 | Mapper jsMap = viewCompiler.compileMap("function(doc){emit(doc._id,null);}", "javascript"); 37 | 38 | for (int i = 0; i < 20000; i++) { 39 | jsMap.map(doc, jsEmiter); 40 | } 41 | assertEquals(20000, jsEmiter.count()); 42 | } 43 | 44 | public void test200SimpleNativeView() { 45 | MockEmiter nativeEmiter = new MockEmiter(); 46 | 47 | Map doc = new HashMap(); 48 | doc.put("_id", "foo"); 49 | 50 | Mapper nativeMap = new Mapper() { 51 | @Override 52 | public void map(Map document, Emitter emitter) { 53 | emitter.emit(document.get("_id"), null); 54 | } 55 | }; 56 | 57 | for (int i = 0; i < 20000; i++) { 58 | nativeMap.map(doc, nativeEmiter); 59 | } 60 | assertEquals(20000, nativeEmiter.count()); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/com/couchbase/lite/javascript/helper/EmitPair.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.lite.javascript.helper; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | public class EmitPair { 7 | Object key; 8 | Object value; 9 | 10 | private ObjectMapper mapper = new ObjectMapper(); 11 | 12 | public EmitPair(Object key, Object value) { 13 | this.key = key; 14 | this.value = value; 15 | } 16 | 17 | public boolean equals(Object aThat) { 18 | if (this == aThat) return true; 19 | if (!(aThat instanceof EmitPair)) return false; 20 | EmitPair that = (EmitPair) aThat; 21 | if (this.key == that.key && this.value == that.value) return true; 22 | 23 | String jsonKey = toJson(this.key); 24 | String jsonValue = toJson(this.value); 25 | String thatJsonKey = toJson(that.key); 26 | String thatJsonValue = toJson(that.value); 27 | 28 | System.out.print(jsonKey + " = " + thatJsonKey); 29 | System.out.print(jsonValue + " = " + thatJsonValue); 30 | if (jsonKey.equals(thatJsonKey) && jsonValue.equals(thatJsonValue)) return true; 31 | 32 | return false; 33 | } 34 | 35 | private String toJson(Object obj) { 36 | String json = null; 37 | try { 38 | json = mapper.writeValueAsString(obj); 39 | } catch (JsonProcessingException e) { 40 | e.printStackTrace(); 41 | } 42 | return json; 43 | } 44 | } -------------------------------------------------------------------------------- /src/test/java/com/couchbase/lite/javascript/helper/MockEmiter.java: -------------------------------------------------------------------------------- 1 | package com.couchbase.lite.javascript.helper; 2 | 3 | import com.couchbase.lite.Emitter; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class MockEmiter implements Emitter { 9 | 10 | private List emited = new ArrayList(); 11 | 12 | @Override 13 | public void emit(Object key, Object value) { 14 | emited.add(new EmitPair(key, value)); 15 | } 16 | 17 | public int count() { 18 | return emited.size(); 19 | } 20 | 21 | public EmitPair get(int i) { 22 | return emited.get(i); 23 | } 24 | } --------------------------------------------------------------------------------