diff --git a/.ci/doc/config.yml b/.ci/doc/config.yml new file mode 100644 index 00000000..9bd2fe99 --- /dev/null +++ b/.ci/doc/config.yml @@ -0,0 +1,18 @@ +--- + +snippets: + mount: /mnt + path: 'doc/**/snippets/*.test.yml' + templates: /mnt/.ci/doc/templates + +runners: + default: java + + java: + service: doc-runner-java + path: /var/snippets/java + build: + cmd: cd /mnt && ./gradlew jar + run: + before: timeout 600 bash -c 'until stat /tmp/runner_is_ready && curl -f -s -o /dev/null http://kuzzle:7512/_now; do sleep 1; done' + cmd: cp /mnt/build/libs/sdk-java-[0-9+].[0-9+].[0-9+].jar /mnt/.ci/doc/project/libs/ && cp {{ snippet.source }} /mnt/.ci/doc/project/src/main/java/SnippetTest.java && cd /mnt/.ci/doc/project/ && ./gradlew build && java -classpath 'libs/sdk-java-3.0.0.jar:' -jar build/libs/project-1.jar diff --git a/.ci/doc/docker-compose.yml b/.ci/doc/docker-compose.yml new file mode 100644 index 00000000..5a2e9223 --- /dev/null +++ b/.ci/doc/docker-compose.yml @@ -0,0 +1,56 @@ +version: '3' + +services: + kuzzle: + image: kuzzleio/kuzzle:2 + ports: + - "7512:7512" + cap_add: + - SYS_PTRACE + depends_on: + - redis + - elasticsearch + environment: + - kuzzle_services__storageEngine__client__node=http://elasticsearch:9200 + - kuzzle_services__internalCache__node__host=redis + - kuzzle_services__memoryStorage__node__host=redis + - kuzzle_services__storageEngine__commonMapping__dynamic=true + - NODE_ENV=production + + redis: + image: redis:5 + + elasticsearch: + image: kuzzleio/elasticsearch:7 + ulimits: + nofile: 65536 + + doc-tests: + image: kuzzleio/snippets-tests + privileged: true + ports: + - '9229:9229' + depends_on: + - kuzzle + - doc-runner-java + volumes: + - ../..:/mnt + - /var/run/docker.sock:/var/run/docker.sock + - snippets:/var/snippets + environment: + - CONFIG_FILE=/mnt/.ci/doc/config.yml + + doc-runner-java: + image: adoptopenjdk/openjdk8 + command: > + bash -c ' + mkdir -p /var/snippets/java; + touch /tmp/runner_is_ready; + tail -f /dev/null + ' + volumes: + - ../..:/mnt + - snippets:/var/snippets + +volumes: + snippets: diff --git a/.ci/doc/project/build.gradle b/.ci/doc/project/build.gradle new file mode 100644 index 00000000..99b9cd83 --- /dev/null +++ b/.ci/doc/project/build.gradle @@ -0,0 +1,31 @@ +plugins { + id 'java' +} + +group 'test.example.java' +version '1' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.12' + compile fileTree(dir: 'libs', include: ['*.jar']) + compile 'com.neovisionaries:nv-websocket-client:2.9' + compile 'com.google.code.gson:gson:2.8.5' +} + +jar { + manifest { + attributes( + 'Class-Path': configurations.compile.collect { it.getName() }.join(' '), + 'Main-Class': 'SnippetTest' + ) + } + from { + configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } + } +} \ No newline at end of file diff --git a/.ci/doc/project/gradle/wrapper/gradle-wrapper.jar b/.ci/doc/project/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..f3d88b1c Binary files /dev/null and b/.ci/doc/project/gradle/wrapper/gradle-wrapper.jar differ diff --git a/.ci/doc/project/gradle/wrapper/gradle-wrapper.properties b/.ci/doc/project/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..718c0f3d --- /dev/null +++ b/.ci/doc/project/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Jan 17 11:19:10 CET 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1-all.zip diff --git a/.ci/doc/project/gradlew b/.ci/doc/project/gradlew new file mode 100755 index 00000000..2fe81a7d --- /dev/null +++ b/.ci/doc/project/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/.ci/doc/project/gradlew.bat b/.ci/doc/project/gradlew.bat new file mode 100644 index 00000000..24467a14 --- /dev/null +++ b/.ci/doc/project/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/.ci/doc/project/libs/.keep b/.ci/doc/project/libs/.keep new file mode 100644 index 00000000..e69de29b diff --git a/.ci/doc/project/settings.gradle b/.ci/doc/project/settings.gradle new file mode 100644 index 00000000..682509ee --- /dev/null +++ b/.ci/doc/project/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'project' diff --git a/.ci/doc/project/src/main/java/.keep b/.ci/doc/project/src/main/java/.keep new file mode 100644 index 00000000..e69de29b diff --git a/.ci/doc/templates/catch.tpl.java b/.ci/doc/templates/catch.tpl.java new file mode 100644 index 00000000..bd56af5f --- /dev/null +++ b/.ci/doc/templates/catch.tpl.java @@ -0,0 +1,25 @@ +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Protocol.WebSocket; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Options.KuzzleOptions; +import java.util.concurrent.ConcurrentHashMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] argv) { + try { + kuzzle = new Kuzzle(new WebSocket("kuzzle")); + kuzzle.connect(); + [snippet-code] + System.out.println("Error"); + } catch (Exception e) { + System.out.println(e.getMessage()); + } finally { + if (kuzzle != null) { + kuzzle.disconnect(); + } + } + } +} \ No newline at end of file diff --git a/.ci/doc/templates/default.tpl.java b/.ci/doc/templates/default.tpl.java new file mode 100644 index 00000000..8bfc6f53 --- /dev/null +++ b/.ci/doc/templates/default.tpl.java @@ -0,0 +1,31 @@ +import io.kuzzle.sdk.Kuzzle; +import java.util.ArrayList; +import io.kuzzle.sdk.Protocol.WebSocket; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Options.KuzzleOptions; +import java.util.concurrent.ConcurrentHashMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.CoreClasses.SearchResult; +import io.kuzzle.sdk.Options.SubscribeOptions; +import io.kuzzle.sdk.Options.UpdateOptions; +import io.kuzzle.sdk.Options.CreateOptions; +import io.kuzzle.sdk.Options.SearchOptions; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] argv) { + try { + kuzzle = new Kuzzle(new WebSocket("kuzzle")); + kuzzle.connect(); + [snippet-code] + System.out.println("Success"); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (kuzzle != null) { + kuzzle.disconnect(); + } + } + } +} \ No newline at end of file diff --git a/.ci/doc/templates/empty.tpl.java b/.ci/doc/templates/empty.tpl.java new file mode 100644 index 00000000..f6c250ed --- /dev/null +++ b/.ci/doc/templates/empty.tpl.java @@ -0,0 +1 @@ +[snippet-code] \ No newline at end of file diff --git a/.ci/doc/templates/print-result-array.tpl.java b/.ci/doc/templates/print-result-array.tpl.java new file mode 100644 index 00000000..c4fd68cd --- /dev/null +++ b/.ci/doc/templates/print-result-array.tpl.java @@ -0,0 +1,30 @@ +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Protocol.WebSocket; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Options.KuzzleOptions; +import io.kuzzle.sdk.Options.SubscribeOptions; +import io.kuzzle.sdk.CoreClasses.Responses.Response; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.ArrayList; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] argv) { + try { + kuzzle = new Kuzzle(new WebSocket("kuzzle")); + kuzzle.connect(); + [snippet-code] + for (Object o : result.get("successes")) { + System.out.println(o); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (kuzzle != null) { + kuzzle.disconnect(); + } + } + } +} \ No newline at end of file diff --git a/.ci/doc/templates/print-result-arraylist.tpl.java b/.ci/doc/templates/print-result-arraylist.tpl.java new file mode 100644 index 00000000..ca5a96dc --- /dev/null +++ b/.ci/doc/templates/print-result-arraylist.tpl.java @@ -0,0 +1,30 @@ +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Protocol.WebSocket; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Options.KuzzleOptions; +import io.kuzzle.sdk.Options.SubscribeOptions; +import io.kuzzle.sdk.CoreClasses.Responses.Response; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.ArrayList; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] argv) { + try { + kuzzle = new Kuzzle(new WebSocket("kuzzle")); + kuzzle.connect(); + [snippet-code] + for (Object o : result) { + System.out.println(o); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (kuzzle != null) { + kuzzle.disconnect(); + } + } + } +} \ No newline at end of file diff --git a/.ci/doc/templates/print-result.tpl.java b/.ci/doc/templates/print-result.tpl.java new file mode 100644 index 00000000..7ab9a27f --- /dev/null +++ b/.ci/doc/templates/print-result.tpl.java @@ -0,0 +1,30 @@ +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Protocol.WebSocket; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Options.KuzzleOptions; +import io.kuzzle.sdk.Options.SubscribeOptions; +import io.kuzzle.sdk.Options.UpdateOptions; +import io.kuzzle.sdk.Options.CreateOptions; +import io.kuzzle.sdk.CoreClasses.Responses.Response; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.ArrayList; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] argv) { + try { + kuzzle = new Kuzzle(new WebSocket("kuzzle")); + kuzzle.connect(); + [snippet-code] + System.out.println(result.toString()); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (kuzzle != null) { + kuzzle.disconnect(); + } + } + } +} \ No newline at end of file diff --git a/.ci/doc/templates/without-connect.tpl.java b/.ci/doc/templates/without-connect.tpl.java new file mode 100644 index 00000000..06da4d92 --- /dev/null +++ b/.ci/doc/templates/without-connect.tpl.java @@ -0,0 +1,20 @@ +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Protocol.WebSocket; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] argv) { + try { + kuzzle = new Kuzzle(new WebSocket("kuzzle")); + [snippet-code] + System.out.println("Success"); + } catch (Exception e) { + System.err.println(e.getMessage()); + } finally { + if (kuzzle != null) { + kuzzle.disconnect(); + } + } + } +} diff --git a/.ci/doc/templates/without-ctor.tpl.java b/.ci/doc/templates/without-ctor.tpl.java new file mode 100644 index 00000000..0050e727 --- /dev/null +++ b/.ci/doc/templates/without-ctor.tpl.java @@ -0,0 +1,15 @@ +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Protocol.WebSocket; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Options.KuzzleOptions; + +public class SnippetTest { + public static void main(String[] argv) { + try { + [snippet-code] + System.out.println("Success"); + } catch (Exception e) { + System.err.println((e.getMessage())); + } + } +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 2e9487e3..ea7a48bf 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,12 @@ build out .idea +bin +*.iml +*.class +bin +.classpath +.project -doc/framework \ No newline at end of file +doc/framework +node_modules diff --git a/.settings/org.eclipse.buildship.core.prefs b/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 00000000..e8895216 --- /dev/null +++ b/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,2 @@ +connection.project.dir= +eclipse.preferences.version=1 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..cd6e3b3f --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,281 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=48 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=48 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=48 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=80 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 00000000..9de95cfa --- /dev/null +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,60 @@ +cleanup.add_default_serial_version_id=true +cleanup.add_generated_serial_version_id=false +cleanup.add_missing_annotations=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=false +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=false +cleanup.always_use_this_for_non_static_method_access=false +cleanup.convert_to_enhanced_for_loop=false +cleanup.correct_indentation=true +cleanup.format_source_code=true +cleanup.format_source_code_changes_only=false +cleanup.make_local_variable_final=true +cleanup.make_parameters_final=false +cleanup.make_private_fields_final=true +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=false +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=true +cleanup.qualify_static_field_accesses_with_declaring_class=false +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.remove_private_constructors=true +cleanup.remove_trailing_whitespaces=true +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=true +cleanup.sort_members_all=true +cleanup.use_blocks=true +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_parentheses_in_expressions=false +cleanup.use_this_for_non_static_field_access=false +cleanup.use_this_for_non_static_field_access_only_if_necessary=true +cleanup.use_this_for_non_static_method_access=false +cleanup.use_this_for_non_static_method_access_only_if_necessary=true +cleanup_profile=_Eclipse [built-in] custom +cleanup_settings_version=2 +eclipse.preferences.version=1 +formatter_profile=_Eclipse [built-in] custom +formatter_settings_version=12 +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=java;javax;org;com; +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.staticondemandthreshold=99 diff --git a/.settings/org.eclipse.ltk.core.refactoring.prefs b/.settings/org.eclipse.ltk.core.refactoring.prefs new file mode 100644 index 00000000..b196c64a --- /dev/null +++ b/.settings/org.eclipse.ltk.core.refactoring.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false diff --git a/.travis.yml b/.travis.yml index 674ad6f2..bdb9085b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,38 +1,45 @@ - env: global: - # BINTRAY_USER - - secure: "LxONQZ8tHhxTqgu+kqx9fMCubCfTQHZsy/3ibE+l72xG8sOAYfj4hB5k1p4kklnv3skeFQEiL6B++B2qRITOEAPRdD8FExkc+UF/TM1rY5aUtjIjoA3uH4n9hYjHirTO5qNKf4KxDr1Zbcn4ISGebJ0EYwE0SG/ptrd06wPp1G8AHshc8XaZgen6gDaik66OWpQkOkmGsRz2EPmIBVgo7L2LGK21DSxE4/PTo+ou0WYCyxyyWSKLTLt1xZpt9LOtk7IckrHl+Nenl6IbV/CjHb3+5vwdifyFQd+K6AVe32iTIVjdxj7rDhEHYD0EqKb79ey+u8p9HquLnGH03gcVBeFQu/qhhQStsiwrD/S9c8jwBjWOOUnVI4bEbqjqxFaRlPfVnRaAjQZLRKHdqxyTJCdC2Ls79LmkqSCyTxM7WBwwgu4Slf6RJSbKJb5naHYlwDuKPbeyHLAYrxgjEHC28bxQiTr5wwBWxE9BLxUcnkFAXzsy3qE74FQOIjvQbtrruLIOGwRGRYtzyfygGA3MfTHug6JwZGngqFf3k+kbznE8fZe7zxMwT63P6/54rR5fU/plLoTNFqdQsZGAfGOSYuHIEzWXOkWxffqsOwxPa1VxQTLD32O95oBcrcvmw4toC2NeFTe/+zZRMfGMbu7QIi0AL3qFpky3j12zcyA/M2I=" - # BINTRAY_KEY - - secure: "Iqn4ImAwFmQeoXXDb5JOsfcunSiSeLvdp4+AEsIeniMhpIk++ZJPDSxecC+NrvndTrxOXVqHEsFUfHnZYvPHMuvg9nhXvz/rmmyYH0hZqkKg2q2qM+Sz2UJBCvs6D1sJv3ZEVi8d6fVx5bbKXMzSE023XFBBK7l8nBsG5ObXBOzTzrus9UP+fk4FXif/QKJNcUSN7rLejUIxMCk36gMQYqYGiiqL3VE60aTpaUh7Vqj/8nCEPcO3K3gXTVybcGBcmsvinV5YEc+5s5ue8eX10ONY0oYF5GFd7aEsrKEFzT2d7MVq0a29cH1rWrxt6q7vXGZNKAdAQrDyRZUz9rMFtqH+2xOgagm22UiUYNlzrn2eDYRBd08X0y043gumdgmOq/CsyaI5bcUSKMr+rsZ2XIzBjefl8MU0xBhtKMO9g9WRfGBxjRbdg0ivRQoVGJbcUXTDl2WrLMgMjt8DT4nQP+PHdIV2FjZVNioqucqmEzfHIJt+hiw7EonGDnZ9uqkW6hm6b4JpGr5QF1yY6kKVCUQxLueUBAVdiZpULdevL7uYEUzdWIES2wTFE7LaWpHqnCOHYVpkIQpdole6+R0OhINhSHK0FW858xhZ2QGjtL1SSh5yzK4th6dpGKCiwMUSGSj5frpIeWPi+GqYoUQz+TvMGLGG2XGfihx74kQE0FA=" - AWS_ACCESS_KEY_ID=AKIAIYAXFUAHXOWP2MJA # AWS_SECRET_ACCESS_KEY - - secure: "dIcQzFpHKRf92cAiMA+SYsudtHWNcbYadVDb7zlJayWGUGy0i4CGwwOoOOrUcWgHxYhdN9XGwvFJTSswjHLRiHEyPFBwW8x/VfaCRS+jAcblMXyWNajvm0930S/3fRv5LA+4UKNmeXMuCGSf35ZqyEIEeuThkIomYvB/tBD1wcMpBUtQfmilLm3sUTaGUnFB651jBHshlYOZ8BAGLLmX1PAfT1wCrpVcrjq5kayNOIilJkwKGSr6q9C0p7+ULNZ4bHsATKLlYNs7Xcs+9a66p1EtKetP72DQsHrr8x3wB2Hhk3U425kmjIoE3gYnF7x3h3EpO5m0rGessbgdRF1SF7XK7Bsj4ukLb4HoktA8G7734ox4848RpH60aKUHRCsiebX7JKgJe1eEwU5BZK8+PFPGH6bI1YG1HQNqthzotTHFXu058uMHnyLv2PmDWWEYMM79fCyuRo8gJJ8GJhDgaGLgtizzEb6grcNW+QwunjA6nP4o7F9o+9b3lfGlsgL595V/CeWLNnHvENkSr67RN2NkDZm6q6EHbOk8AWtQc24mVawCwCbcJjp0sPkbQdCHUXSBNXjdwrvJLA3h94A2uVEmrV7mzMdfj+i9X3IS/HXRLeQk6Ivq2s/b1W6c7rBfz4zZUO7Uu5iYpVzT71yNFra13JkW3REFgHgETEvGkko=" - - -sudo: true - + - secure: NElUP03Z1jbkOO20zYOo6WTdXrHa+b1UbMQJJX1rvG8wLHcEEid5m5VUa9UdSrBT4OxeVLKTVqEtEgFshz8Jjcc7JJ4pZBtGq4ty+S+nG6F9DJ+IMS2kD8h5qtoqh1TBLhov19s0mRNCG53No2+8VSk8STAeSG7x2hL2PAgJq3LCCy5lYVbmhnrCXObtd1a7Nq8XV7EHM+R9aITq3+jKa/NpdADoUv/WcoQAqjc8W3GhACRiNxRaGM58OF2WTojLM5fD3wwuicGkcsBkZkxho4cs0u36EEoxhZuy9U2/Emp7uhs9yCrhY0AwqYbSqvZ6jiwtJflvHHAsW2ZTgHWUekKippAyPIqF+QTeBvkg+q7tabOkfQLaZcREDzUBMI5AQiIW0Sv1fTPEs5jJv2+dE4bzi6BJmzFFGE0iHt4Nui7TLYMeAN17RYB5rJK50AGBA42Puzjr8CaV1FfnqLXOwiDXjGwvz7iHk4MMHFT/vvLcgDgHM16SM5QvhfbfX6Aj13VIG9lWUfKsalMSug8+zrXadtnZoz5XPskw1oA2iEUmgNzS33EVedgtxWDykadn3zhA+Ii+4C+Gge1dPG0sNXYiyI0/XKwlHBe6/Ar/DzKAf9Fo7/Z2haYGHC8XXmblagzVTxqX1FZVeiI3kyDBtduMSILU5ir5VA0dNtGdKVY= +# ------------------------ +# Jobs configuration +# ------------------------ jobs: include: - stage: Tests name: Dead link check - if: type = pull_request OR type = push AND branch =~ /^master|[0-9]+-(dev|stable)$/ OR type = cron + if: + type = pull_request OR type = push AND branch =~ /^master|[0-9]+-(dev|stable)$/ + OR type = cron language: node_js - node_js: 10 - + node_js: 12 before_script: + + - npm ci - npm run doc-prepare - - npm run --prefix doc/framework clone-repos + - $(npm bin)/kuzdoc iterate-repos:install --repos_path doc/framework/.repos/ + - $(npm bin)/kuzdoc framework:link -d /sdk/java/3/ -v 3 script: - gem install typhoeus - - HYDRA_MAX_CONCURRENCY=20 npm run --prefix doc/framework dead-links + - cd doc/framework/ && HYDRA_MAX_CONCURRENCY=20 ruby .ci/dead-links.rb -p src/sdk/java/3/ + + - stage: Tests + name: Documentation Snippets + if: type = pull_request OR type = push AND branch =~ /^master|[0-9]+-dev$/ OR type = cron + language: node_js + node_js: 12 + script: + - docker-compose -f .ci/doc/docker-compose.yml run doc-tests index - stage: Deployment Doc Dev name: Deploy next-docs.kuzzle.io - if: type = push AND branch =~ .*-dev + if: type = push AND branch =~ /^[0-9]+-dev$/ language: node_js - node_js: 10 + node_js: 12 env: + - BRANCH=dev - NODE_ENV=production - S3_BUCKET=docs-next.kuzzle.io - CLOUDFRONT_DISTRIBUTION_ID=E2ZCCEK9GRB49U @@ -40,12 +47,14 @@ jobs: addons: apt: + update: true packages: - python - python-pip install: - pip install awscli --upgrade --user + - npm ci script: - npm run doc-prepare @@ -56,6 +65,8 @@ jobs: script: - npm run doc-upload skip_cleanup: true + on: + all_branches: true after_deploy: - npm run doc-cloudfront @@ -64,56 +75,76 @@ jobs: name: Deploy docs.kuzzle.io if: type = push AND branch =~ /^master|[0-9]+-stable$/ language: node_js - node_js: 10 + node_js: 12 env: - NODE_ENV=production - S3_BUCKET=docs.kuzzle.io - CLOUDFRONT_DISTRIBUTION_ID=E3D6RP0POLCJMM - AWS_DEFAULT_REGION=us-west-2 - addons: apt: packages: - python - python-pip - install: - pip install awscli --upgrade --user - + - npm ci script: - npm run doc-prepare - npm run doc-build - deploy: provider: script script: - npm run doc-upload skip_cleanup: true - + on: + all_branches: true after_deploy: - npm run doc-cloudfront + - stage: Builds + name: Build SDK Java + jdk: openjdk8 + sudo: false + before_cache: + - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + cache: + directories: + - "$HOME/.gradle/caches/" + - "$HOME/.gradle/wrapper/" + install: + - cd $TRAVIS_BUILD_DIR/ + - ./gradlew assemble + script: + - ./gradlew build - - stage: Deployment - name: Deploy to Bintray - if: branch = master AND tag IS present AND type != cron + - stage: Unit tests + name: Unit tests SDK Java language: java - - jdk: - - openjdk8 - + jdk: openjdk8 + sudo: false + before_cache: + - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + cache: + directories: + - "$HOME/.gradle/caches/" + - "$HOME/.gradle/wrapper/" + install: + - cd $TRAVIS_BUILD_DIR/ script: - bash gradlew test jacocoTestReport - - notifications: - email: false - - after_success: - - bash <(curl -s https://codecov.io/bash) - - deploy: - provider: script - script: ./gradlew bintrayUpload - skip_cleanup: true - on: - condition: $TRAVIS_BRANCH = master + - ./gradlew test + +stages: + - name: Unit Tests + if: type =~ /(cron|push|pull_request)/ AND branch =~ /^master|[0-9]+-(dev|stable)$/ + - name: Builds + if: type =~ /(cron|push|pull_request)/ AND branch =~ /^master|[0-9]+-(dev|stable)$/ + +notifications: + slack: + rooms: + - secure: ACjz4TJEYBEzmwVOYrCNnr4+jC0FaX+qh150QacYGIgaQYL+U3xLEQmWNlZ3oxaPPMDAk42m+diHolqNwh6qsOWaPSWRlGfLKhHLSzRI98bhF7HQ+3eLMYmx7y7SKwRzyRjus0jgxp0Kc2mq0nhKqv+7rarQtIgWlC1PLrzZ35CUbUlqYSoeYAlXoyDB1eZgYsvjt+eC5yCvGePsfKbupWC2/hIVl+qZ+9AhVmOfiMv7daFW29Vu300aoY+0IqwX7jHGcmHn/7QCRsx0IBy/SL24TzfSV9SUSnbjK4fTrcrhjYDEZdH1lpvDtvr50GgkrTjy1wPVz8XIyCZ7LZolylkx+nR1MWyvum20QRFub2Qhz/+rS+OFiQZ8H01BPuklLUTSQhBksfpGBck3d2yNLiTqGEVWYTnZ9mkCnMQ3BzJXEF04KLHG7wYn2rk6wjPghVmFQH5GMsxM5v33CFgcNzp6lRJOX9CmjZosck6o9SA0WlazHH/CLWWKk1wrQ1ygDayW5m+N/o58UIxgW2LIUlp4tV1z/bRtO2yTd020yWchlKPVmf1A5OMfigJNMRsQGNZNadS7qA2M394OJw3/Hg+0EVF8gai/V8FRijmkxmhYyCIYMcjaGwx8JxfoMrRKcM76haBAhg0JQxsSVKzyXfONGzd5DXjcxSGZ2wuEdu0= + on_success: never + on_failure: always diff --git a/README.md b/README.md index a5e7b9fd..0d236d14 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ https://bintray.com/kuzzle/maven ```xml io.kuzzle - kuzzle-sdk-java + sdk-java 2.0.0 pom @@ -52,11 +52,11 @@ https://bintray.com/kuzzle/maven ### Gradle ```groovy -compile 'io.kuzzle:kuzzle-sdk-java:2.0.0' +compile 'io.kuzzle:sdk-java:2.0.0' ``` For amd64: ```groovy -compile 'io.kuzzle:kuzzle-sdk-java:2.0.0' +compile 'io.kuzzle:sdk-java:2.0.0' ``` diff --git a/build.gradle b/build.gradle index 4ab207a4..69729b57 100644 --- a/build.gradle +++ b/build.gradle @@ -1,33 +1,30 @@ -/* - * This file was generated by the Gradle 'init' task. - * - * This is a general purpose Gradle build. - * Learn how to create Gradle builds at https://guides.gradle.org/creating-new-gradle-builds/ - */ - -buildscript { - repositories { - jcenter() - } -} +import org.gradle.api.JavaVersion plugins { id "com.jfrog.bintray" version "1.7.3" id 'jacoco' + id 'java' } -group = 'io.kuzzle' -version = '2.0.0' - allprojects { repositories { jcenter() } + apply plugin: 'idea' apply plugin: 'maven-publish' apply plugin: 'java' apply plugin: 'java-library' } +group 'io.kuzzle' +version '3.0.0' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + task sourcesJar(type: Jar, dependsOn: classes) { classifier = 'sources' from sourceSets.main.allSource @@ -86,12 +83,12 @@ publishing { artifact sourcesJar artifact javadocJar groupId 'io.kuzzle' - artifactId 'kuzzle-sdk-java' + artifactId 'sdk-java' version version pom.withXml { def root = asNode() root.appendNode('description', 'Kuzzle JAVA SDK') - root.appendNode('name', 'kuzzle-sdk-java') + root.appendNode('name', 'sdk-java') root.appendNode('url', 'https://github.com/kuzzleio/sdk-java') root.children().last() + pomConfig } @@ -100,8 +97,8 @@ publishing { } dependencies { - compile group: 'org.json', name: 'json', version: '20180813' - compile 'tech.gusavila92:java-android-websocket-client:1.2.2' + implementation 'com.neovisionaries:nv-websocket-client:2.9' + implementation 'com.google.code.gson:gson:2.8.5' testImplementation 'junit:junit:4.12' testImplementation 'org.hamcrest:hamcrest-junit:2.0.0.0' testImplementation 'org.mockito:mockito-core:1.9.5' @@ -117,15 +114,14 @@ jacocoTestReport { check.dependsOn jacocoTestReport -sourceSets { - test { - java { - srcDirs = ["test"] - } - } +compileJava { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +test { + useJUnit() + + maxHeapSize = '1G' } -artifacts { - archives sourcesJar - archives javadocJar -} \ No newline at end of file diff --git a/doc/2/core-classes/collection-mapping/apply/index.md b/doc/2/core-classes/collection-mapping/apply/index.md deleted file mode 100644 index 8dab0698..00000000 --- a/doc/2/core-classes/collection-mapping/apply/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -code: true -type: page -title: apply -description: CollectionMapping:apply ---- - -# apply - -Applies the new mapping to the collection. - ---- - -## apply([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns this `CollectionMapping` object to allow chaining. - ---- - -## Callback Response - -Returns the updated `CollectionMapping` object. - -## Usage - -<<< ./snippets/apply-1.java diff --git a/doc/2/core-classes/collection-mapping/apply/snippets/apply-1.java b/doc/2/core-classes/collection-mapping/apply/snippets/apply-1.java deleted file mode 100644 index 0fc3a79e..00000000 --- a/doc/2/core-classes/collection-mapping/apply/snippets/apply-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -dataMapping.apply(new ResponseListener() { - @Override - public void onSuccess(CollectionMapping object) { - // called once the mapping action has been completed - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/collection-mapping/constructor/index.md b/doc/2/core-classes/collection-mapping/constructor/index.md deleted file mode 100644 index 5627fb6a..00000000 --- a/doc/2/core-classes/collection-mapping/constructor/index.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -code: true -type: page -title: constructor -description: CollectionMapping:constructor -order: 1 ---- - -# CollectionMapping - -When creating a new collection in the persistent data storage layer, Kuzzle uses a default mapping. -This means that, by default, you won't be able to exploit the full capabilities of our persistent data storage layer (currently handled by [ElasticSearch](https://www.elastic.co/products/elasticsearch)), and your searches may suffer from below-average performance, depending on the amount of data you stored in a collection and the complexity of your database. - -The CollectionMapping object allows you to get the current mapping in a collection and to modify it if necessary. - -:::info -Once a field mapping has been set, it cannot be removed without reconstructing the collection. -::: - ---- - -## CollectionMapping(Collection, [mapping]) - -| Arguments | Type | Description | -| ------------ | ---------------------------------------------------- | --------------------------------- | -| `Collection` | [Collection](/sdk/java/2/core-classes/collection) | An instantiated Collection object | -| `mapping` | JSON Object | Optional mapping | - ---- - -## Properties - -| Property name | Type | Description | get/set | -| ------------- | ----------- | --------------------------------------------- | ------- | -| `headers` | JSON Object | Common headers for all sent documents. | get/set | -| `mapping` | object | Easy-to-understand list of mappings per field | get/set | - -**Note:** the `headers` property is inherited from the provided [Collection](/sdk/java/2/core-classes/collection) object and can be overrided - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/collection-mapping/constructor/snippets/constructor-1.java b/doc/2/core-classes/collection-mapping/constructor/snippets/constructor-1.java deleted file mode 100644 index 179c1145..00000000 --- a/doc/2/core-classes/collection-mapping/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,9 +0,0 @@ - -CollectionMapping dataMapping = new CollectionMapping(dataCollection); - -JSONObject mapping = new JSONObject(); -JSONObject type = new JSONObject(); -type.put("type", "string"); -mapping.put("foo", type); - -CollectionMapping dataMapping = new CollectionMapping(dataCollection, mapping); diff --git a/doc/2/core-classes/collection-mapping/index.md b/doc/2/core-classes/collection-mapping/index.md deleted file mode 100644 index e2a17cc9..00000000 --- a/doc/2/core-classes/collection-mapping/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: CollectionMapping -description: CollectionMapping documentation ---- diff --git a/doc/2/core-classes/collection-mapping/refresh/index.md b/doc/2/core-classes/collection-mapping/refresh/index.md deleted file mode 100644 index 1ef27ec2..00000000 --- a/doc/2/core-classes/collection-mapping/refresh/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: refresh -description: CollectionMapping:refresh ---- - -# refresh - -Instantiates a new CollectionMapping object with an up-to-date content. - ---- - -## refresh([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the updated `CollectionMapping` object. - -## Usage - -<<< ./snippets/refresh-1.java diff --git a/doc/2/core-classes/collection-mapping/refresh/snippets/refresh-1.java b/doc/2/core-classes/collection-mapping/refresh/snippets/refresh-1.java deleted file mode 100644 index 6c562b46..00000000 --- a/doc/2/core-classes/collection-mapping/refresh/snippets/refresh-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -dataMapping.refresh(new ResponseListener() { - @Override - public void onSuccess(CollectionMapping object) { - // called once the mapping has been retrieved from Kuzzle - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/collection-mapping/set-headers/index.md b/doc/2/core-classes/collection-mapping/set-headers/index.md deleted file mode 100644 index b081b8b0..00000000 --- a/doc/2/core-classes/collection-mapping/set-headers/index.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -code: true -type: page -title: setHeaders -description: CollectionMapping:setHeaders ---- - -# setHeaders - -This is a helper function returning itself, allowing to easily chain calls. - ---- - -## setHeaders(content, [replace]) - -| Arguments | Type | Description | -| --------- | ----------- | ------------------------------------------------------------------------- | -| `content` | JSON Object | New content | -| `replace` | boolean | true: replace the current content with the provided data, false: merge it | - -**Note:** by default, the `replace` argument is set to `false` - ---- - -## Return value - -Returns this `CollectionMapping` object to allow chaining. - -## Usage - -<<< ./snippets/set-headers-1.java diff --git a/doc/2/core-classes/collection-mapping/set-headers/snippets/set-headers-1.java b/doc/2/core-classes/collection-mapping/set-headers/snippets/set-headers-1.java deleted file mode 100644 index 4ba87e2c..00000000 --- a/doc/2/core-classes/collection-mapping/set-headers/snippets/set-headers-1.java +++ /dev/null @@ -1,4 +0,0 @@ - -JSONObject headers = new JSONObject(); -headers.put("someContent", "someValue"); -dataMapping.setHeaders(headers, true); diff --git a/doc/2/core-classes/collection-mapping/set/index.md b/doc/2/core-classes/collection-mapping/set/index.md deleted file mode 100644 index 7c8e9199..00000000 --- a/doc/2/core-classes/collection-mapping/set/index.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -code: true -type: page -title: set -description: CollectionMapping:set ---- - -# set - -Adds or updates a field mapping. - -:::info -Changes made by this function won't be applied until you call the `apply` method -::: - ---- - -## set(field, mapping) - -| Arguments | Type | Description | -| --------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| `field` | string | Name of the field from which the mapping is to be added or updated | -| `mapping` | JSON Object | Mapping for this field, following the [Elasticsearch Mapping format](https://www.elastic.co/guide/en/elasticsearch/reference/5.x/mapping.html) | - ---- - -## Return Value - -Returns this `CollectionMapping` object to allow chaining. - -## Usage - -<<< ./snippets/set-1.java diff --git a/doc/2/core-classes/collection-mapping/set/snippets/set-1.java b/doc/2/core-classes/collection-mapping/set/snippets/set-1.java deleted file mode 100644 index 8631d14a..00000000 --- a/doc/2/core-classes/collection-mapping/set/snippets/set-1.java +++ /dev/null @@ -1,7 +0,0 @@ - -JSONObject mapping = new JSONObject(); -mapping.put("type", "string"); -mapping.put("index", "analyzed"); -mapping.put("null_value", ""); - -dataMapping.set("field", mapping); diff --git a/doc/2/core-classes/collection/collection-mapping/index.md b/doc/2/core-classes/collection/collection-mapping/index.md deleted file mode 100644 index 68e15885..00000000 --- a/doc/2/core-classes/collection/collection-mapping/index.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -code: true -type: page -title: collectionMapping -description: Collection:collectionMapping ---- - -# collectionMapping - -Creates a new [CollectionMapping](/sdk/java/2/core-classes/collection-mapping) object, using its constructor. - ---- - -## collectionMapping([mapping]) - -| Arguments | Type | Description | -| --------- | ----------- | ---------------- | -| `mapping` | JSON Object | Optional mapping | - ---- - -## Return Value - -Returns the newly created [CollectionMapping](/sdk/java/2/core-classes/collection-mapping) object. - -## Usage - -<<< ./snippets/collection-mapping-1.java diff --git a/doc/2/core-classes/collection/collection-mapping/snippets/collection-mapping-1.java b/doc/2/core-classes/collection/collection-mapping/snippets/collection-mapping-1.java deleted file mode 100644 index 2205594c..00000000 --- a/doc/2/core-classes/collection/collection-mapping/snippets/collection-mapping-1.java +++ /dev/null @@ -1,15 +0,0 @@ - -CollectionMapping dataMapping = kuzzle - .collection("collection", "index") - .collectionMapping(new JSONObject().put("someFiled", new JSONObject().put("type", "string").put("index", "analyzed")) - .apply(new ResponseListener() { - @Override - public void onSuccess(CollectionMapping object) { - // called once the mapping action has been completed - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/constructor/index.md b/doc/2/core-classes/collection/constructor/index.md deleted file mode 100644 index 4506e554..00000000 --- a/doc/2/core-classes/collection/constructor/index.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -code: true -type: page -title: constructor -description: Collection:constructor -order: 1 ---- - -# Collection - -In Kuzzle, you manipulate documents and subscriptions, both related to collections. - -A collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents, or like a room for pub/sub messages. - ---- - -## Collection(kuzzle, collection, index) - -| Arguments | Type | Description | -| ------------ | ------ | ------------------------------------------------------ | -| `kuzzle` | object | Kuzzle object | -| `collection` | string | The name of the collection you want to manipulate | -| `index` | string | Name of the index containing the collection | - -**Note:** We recommend you instantiate a Collection object by calling [Kuzzle.collection](/sdk/java/2/core-classes/kuzzle/collection) rather than using the constructor directly - ---- - -## Properties - -| Property name | Type | Description | get/set | -| ------------- | ------ | -------------------------------------------------------- | ------- | -| `collection` | string | The name of the collection handled by this instance | get | -| `index` | object | Name of the index containing the collection | get | -| `headers` | object | Headers for all sent documents. | get/set | -| `kuzzle` | object | linked Kuzzle instance | get | - -**Note:** the `headers` property is inherited from the main `Kuzzle` object and can be overrided - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/collection/constructor/snippets/constructor-1.java b/doc/2/core-classes/collection/constructor/snippets/constructor-1.java deleted file mode 100644 index 6a97b6a3..00000000 --- a/doc/2/core-classes/collection/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,2 +0,0 @@ - - Collection myCollection = new Collection(kuzzle, "my-collection", "my-index"); diff --git a/doc/2/core-classes/collection/count/index.md b/doc/2/core-classes/collection/count/index.md deleted file mode 100644 index 631d4abc..00000000 --- a/doc/2/core-classes/collection/count/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: count -description: Collection:count ---- - -# count - -Returns the number of documents matching the provided set of filters. - -:::info -There is a small delay between the time a document is created and its availability in our search layer (usually a couple of seconds). That means that a document that was just created might not be immediately returned by this function. -::: - ---- - -## count(filters, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------- | -| `filters` | JSON Object | Filters in [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/5.x/query-dsl.html) format | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a count for the number of document matches as an `integer`. - -## Usage - -<<< ./snippets/count-1.java - -> Callback response: - -```json -12 -``` diff --git a/doc/2/core-classes/collection/count/snippets/count-1.java b/doc/2/core-classes/collection/count/snippets/count-1.java deleted file mode 100644 index f9f9ea2a..00000000 --- a/doc/2/core-classes/collection/count/snippets/count-1.java +++ /dev/null @@ -1,16 +0,0 @@ - -JSONObject filters = new JSONObject(); - -kuzzle - .collection("collection", "index") - .count(filters, new ResponseListener() { - @Override - public void onSuccess(Integer object) { - // Handle success - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/create-document/index.md b/doc/2/core-classes/collection/create-document/index.md deleted file mode 100644 index dcc286e3..00000000 --- a/doc/2/core-classes/collection/create-document/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -code: true -type: page -title: createDocument -description: Collection:createDocument ---- - -# createDocument - -Create a new document in Kuzzle and instantiate a [Document](/sdk/java/2/core-classes/document) object. - ---- - -## createDocument(Document, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------- | -| `Document` | object | [Document](/sdk/java/2/core-classes/document) object | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## createDocument([id], content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------- | -| `id` | string | Optional document identifier | -| `content` | JSON object | Content of the document to create | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `volatile` | JSON object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | -| `ifExist` | string | If the same document already exists: resolves to an `error`. Replaces the existing document if set to `replace` | `false` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns a [Document](/sdk/java/2/core-classes/document) object containing the newly created document. - -## Usage - -<<< ./snippets/create-document-1.java diff --git a/doc/2/core-classes/collection/create-document/snippets/create-document-1.java b/doc/2/core-classes/collection/create-document/snippets/create-document-1.java deleted file mode 100644 index 7f4681c6..00000000 --- a/doc/2/core-classes/collection/create-document/snippets/create-document-1.java +++ /dev/null @@ -1,22 +0,0 @@ - -Document myDocument = new Document(collection); -myDocument.setContent("title", "foo"); -myDocument.setContent("content", "bar"); - -Options opts = new Options(); -opts.setIfExist = "replace"; - -kuzzle - .collection("collection", "index") - .createDocument(myDocument, new ResponseListener() { - @Override - public void onSuccess(Document object) { - // callback called once the create action has been completed - // => the result is a Document object - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/create/index.md b/doc/2/core-classes/collection/create/index.md deleted file mode 100644 index 75a38919..00000000 --- a/doc/2/core-classes/collection/create/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -code: true -type: page -title: create -description: Collection:create ---- - -# create - -Creates a new [collection](/core/1/guides/essentials/store-access-data) in the provided `index`. - - - -You can also provide an optional data mapping that allow you to exploit the full capabilities of our -persistent data storage layer, [ElasticSearch](https://www.elastic.co/products/elasticsearch) (check here the [mapping capabilities of ElasticSearch](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/mapping.html)). - -This method will only update the mapping if the collection already exists. - ---- - -## create([mapping], [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------- | -| `mapping` | JSON Object | Optional data mapping | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Ralue - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. - -## Usage - -<<< ./snippets/create-1.java - -> Callback response: - -```json -{ - "status": 200, - "error": null, - "requestId": "", - "controller": "collection", - "action": "create", - "collection": "", - "index": "index", - "volatile": null, - "result": { - "acknowledged": true - } -} -``` diff --git a/doc/2/core-classes/collection/create/snippets/create-1.java b/doc/2/core-classes/collection/create/snippets/create-1.java deleted file mode 100644 index 137e24a4..00000000 --- a/doc/2/core-classes/collection/create/snippets/create-1.java +++ /dev/null @@ -1,26 +0,0 @@ - -// Optional: a mapping can be provided and will be -// applied when the collection is created -JSONObject mapping = new JSONObject() - .put("properties", new JSONObject() - .put("field1", new JSONObject().put("type", "")) - .put("field2", new JSONObject().put("type", "")) - ); - -kuzzle - .collection("collection", "index") - .create(mapping, new ResponseListener() { - @Override - public void onSuccess(JSONObject object) { - // callback called once the create operation has completed - // => the result is a JSON object containing the raw Kuzzle response: - // { - // acknowledged: true - // } - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/delete-document/index.md b/doc/2/core-classes/collection/delete-document/index.md deleted file mode 100644 index 27e216a8..00000000 --- a/doc/2/core-classes/collection/delete-document/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -code: true -type: page -title: deleteDocument -description: Collection:deleteDocument ---- - -# deleteDocument - -Delete a stored document, or all stored documents matching a search filter. - -:::info -There is a small delay between the time a document is deleted and it being reflected in the search layer (usually a couple of seconds). That means that a document that was just deleted might still be returned by this function. -::: - ---- - -## deleteDocument(documentId, [options], [callback]) - -| Arguments | Type | Description | -| ------------ | ----------- | -------------------------- | -| `documentId` | string | Unique document identifier | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## deleteDocument(filters, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------- | -| `filters` | JSON object | Filters in [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/5.x/query-dsl.html) format | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `volatile` | JSON object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns an `array` containing the ids of the deleted documents. - -## Usage - -<<< ./snippets/delete-document-1.java - -> Callback response: - -```json -["AVCoeBkimsySTKTfa8AX"] -``` diff --git a/doc/2/core-classes/collection/delete-document/snippets/delete-document-1.java b/doc/2/core-classes/collection/delete-document/snippets/delete-document-1.java deleted file mode 100644 index 9bd203ba..00000000 --- a/doc/2/core-classes/collection/delete-document/snippets/delete-document-1.java +++ /dev/null @@ -1,36 +0,0 @@ - -// Deleting one document -kuzzle - .collection("collection", "index") - .deleteDocument("document unique ID", new ResponseListener() { - @Override - public void onSuccess(String object) { - // The resulting string contains the deleted document ID - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); - -// Deleting multiple documents -JSONObject equalsFilter = new JSONObject() - .put("filter", new JSONObject() - .put("equals", - new JSONObject().put("title", "foo") - )); - -kuzzle - .collection("collection", "index") - .deleteDocument(equalsFilter, new ResponseListener() { - @Override - public void onSuccess(String[] object) { - // The resulting object contains the list of deleted document IDs - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/delete-specifications/index.md b/doc/2/core-classes/collection/delete-specifications/index.md deleted file mode 100644 index bad83f54..00000000 --- a/doc/2/core-classes/collection/delete-specifications/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: deleteSpecifications -description: Collection:deleteSpecifications ---- - -# deleteSpecifications - -Delete specifications linked to the collection object. - ---- - -## deleteSpecifications([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer indexation to return (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - -## Usage - -<<< ./snippets/delete-specifications-1.java - -> Callback response: - -```json -{ - "acknowledged": true -} -``` diff --git a/doc/2/core-classes/collection/delete-specifications/snippets/delete-specifications-1.java b/doc/2/core-classes/collection/delete-specifications/snippets/delete-specifications-1.java deleted file mode 100644 index 5f824b96..00000000 --- a/doc/2/core-classes/collection/delete-specifications/snippets/delete-specifications-1.java +++ /dev/null @@ -1,15 +0,0 @@ - -// Deleting one document -kuzzle - .collection("collection", "index") - .deleteSpecifications(new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/document/index.md b/doc/2/core-classes/collection/document/index.md deleted file mode 100644 index 22b8c904..00000000 --- a/doc/2/core-classes/collection/document/index.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -code: true -type: page -title: document -description: Collection:document ---- - -# document - -Creates a new [Document](/sdk/java/2/core-classes/document) object, using its constructor. - ---- - -## document([id], [content]) - -| Arguments | Type | Description | -| --------- | ----------- | --------------------------- | -| `id` | string | Optional document unique ID | -| `content` | JSON object | Optional document content | - ---- - -## Return Value - -Returns the newly created [Document](/sdk/java/2/core-classes/document) object. - -## Usage - -<<< ./snippets/document-1.java diff --git a/doc/2/core-classes/collection/document/snippets/document-1.java b/doc/2/core-classes/collection/document/snippets/document-1.java deleted file mode 100644 index 26a9c121..00000000 --- a/doc/2/core-classes/collection/document/snippets/document-1.java +++ /dev/null @@ -1,5 +0,0 @@ - -Document document = kuzzle - .collection("collection", "index") - .document("id", new JSONObject().put("some", "content")) - .save(); diff --git a/doc/2/core-classes/collection/fetch-document/index.md b/doc/2/core-classes/collection/fetch-document/index.md deleted file mode 100644 index f9b1edbd..00000000 --- a/doc/2/core-classes/collection/fetch-document/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -code: true -type: page -title: fetchDocument -description: Collection:fetchDocument ---- - -# fetchDocument - -Retrieves a single stored document using its unique document ID, and returns it as a [Document](/sdk/java/2/core-classes/document) object. - ---- - -## fetchDocument(documentId, [options], callback) - -| Arguments | Type | Description | -| ------------ | ----------- | ------------------------------ | -| `documentId` | string | Unique document identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a [Document](/sdk/java/2/core-classes/document) object. - -## Usage - -<<< ./snippets/fetch-document-1.java diff --git a/doc/2/core-classes/collection/fetch-document/snippets/fetch-document-1.java b/doc/2/core-classes/collection/fetch-document/snippets/fetch-document-1.java deleted file mode 100644 index 1c209d32..00000000 --- a/doc/2/core-classes/collection/fetch-document/snippets/fetch-document-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .collection("collection", "index") - .fetchDocument("documentId", new ResponseListener() { - @Override - public void onSuccess(Document object) { - // result is a Document object - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/get-mapping/index.md b/doc/2/core-classes/collection/get-mapping/index.md deleted file mode 100644 index 0f9831e2..00000000 --- a/doc/2/core-classes/collection/get-mapping/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: getMapping -description: Collection:getMapping ---- - -# getMapping - -Retrieves the current mapping of this collection as a [CollectionMapping](/sdk/java/2/core-classes/collection-mapping) object. - ---- - -## getMapping([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a [CollectionMapping](/sdk/java/2/core-classes/collection-mapping) object. - -## Usage - -<<< ./snippets/get-mapping-1.java diff --git a/doc/2/core-classes/collection/get-mapping/snippets/get-mapping-1.java b/doc/2/core-classes/collection/get-mapping/snippets/get-mapping-1.java deleted file mode 100644 index 0fdd7119..00000000 --- a/doc/2/core-classes/collection/get-mapping/snippets/get-mapping-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .collection("collection", "index") - .getMapping(new ResponseListener() { - @Override - public void onSuccess(CollectionMapping object) { - // result is a CollectionMapping object - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/get-specifications/index.md b/doc/2/core-classes/collection/get-specifications/index.md deleted file mode 100644 index b1925896..00000000 --- a/doc/2/core-classes/collection/get-specifications/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: getSpecifications -description: Collection:getSpecifications ---- - -# getSpecifications - -Retrieves the specifications linked to the collection object. - ---- - -## getSpecifications([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - -## Usage - -<<< ./snippets/get-specifications-1.java - -> Callback response - -```json -{ - "validation": { - "strict": "true", - "fields": { - "foo": { - "mandatory": "true", - "type": "string", - "defaultValue": "bar" - } - } - }, - "index": "index", - "collection": "collection" -} -``` diff --git a/doc/2/core-classes/collection/get-specifications/snippets/get-specifications-1.java b/doc/2/core-classes/collection/get-specifications/snippets/get-specifications-1.java deleted file mode 100644 index f2cccbd8..00000000 --- a/doc/2/core-classes/collection/get-specifications/snippets/get-specifications-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .collection("collection", "index") - .getSpecifications(new ResponseListener() { - @Override - public void onSuccess(JSONObject specifications) { - // specifications is a JSONObject - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/index.md b/doc/2/core-classes/collection/index.md deleted file mode 100644 index a0b54cf6..00000000 --- a/doc/2/core-classes/collection/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: Collection -description: Collection documentation ---- diff --git a/doc/2/core-classes/collection/mcreate-document/index.md b/doc/2/core-classes/collection/mcreate-document/index.md deleted file mode 100644 index f488edfb..00000000 --- a/doc/2/core-classes/collection/mcreate-document/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: mcreateDocument -description: Collection:mcreateDocument ---- - -# mCreateDocument - -Create the input [Documents](/sdk/java/2/core-classes/document). - ---- - -## mCreateDocument(documents, [options], [callback]) - -| Arguments | Type | Description | -| ----------- | ----------- | ------------------------------------------------------------------- | -| `documents` | Document[] | Array of [Document](/sdk/java/2/core-classes/document) to create | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. -Can return a 206 partial error in cases where some documents could not be created. - -## Usage - -<<< ./snippets/mcreate-document-1.java - -> Callback response: - -```json -{ - "hits": [{ "first": "document" }, { "second": "document" }], - "total": 2 -} -``` diff --git a/doc/2/core-classes/collection/mcreate-document/snippets/mcreate-document-1.java b/doc/2/core-classes/collection/mcreate-document/snippets/mcreate-document-1.java deleted file mode 100644 index 548fe332..00000000 --- a/doc/2/core-classes/collection/mcreate-document/snippets/mcreate-document-1.java +++ /dev/null @@ -1,25 +0,0 @@ - -Document firstDocument = new Document(collection, "doc1"); -firstDocument.setContent("title", "foo"); -firstDocument.setContent("content", "bar"); - -Document secondDocument = new Document(collection, "doc2"); -secondDocument.setContent("title", "foo"); -secondDocument.setContent("content", "bar"); - -Document[] documents = new Document[]{firstDocument, secondDocument}; - -kuzzle - .collection("collection", "index") - .mCreateDocument(documents, new ResponseListener() { - @Override - public void onSuccess(JSONObject object) { - // callback called once the mCreate operation has completed - // => the result is a JSON object containing the raw Kuzzle response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/mcreate-or-replace-document/index.md b/doc/2/core-classes/collection/mcreate-or-replace-document/index.md deleted file mode 100644 index cec209e6..00000000 --- a/doc/2/core-classes/collection/mcreate-or-replace-document/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: mcreateOrReplaceDocument -description: Collection:mcreateOrReplaceDocument ---- - -# mCreateOrReplaceDocument - -Create or replace the input [Documents](/sdk/java/2/core-classes/document). - ---- - -## mCreateOrReplaceDocument(documents, [options], [callback]) - -| Arguments | Type | Description | -| ----------- | ----------- | ------------------------------------------------------------------------------ | -| `documents` | Document[] | Array of [Document](/sdk/java/2/core-classes/document) to create or replace | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. -Can return a 206 partial error in cases where some documents could not be created or replaced. - -## Usage - -<<< ./snippets/mcreate-or-replace-document-1.java - -> Callback response: - -```json -{ - "hits": [{ "first": "document" }, { "second": "document" }], - "total": 2 -} -``` diff --git a/doc/2/core-classes/collection/mcreate-or-replace-document/snippets/mcreate-or-replace-document-1.java b/doc/2/core-classes/collection/mcreate-or-replace-document/snippets/mcreate-or-replace-document-1.java deleted file mode 100644 index 7f79fecb..00000000 --- a/doc/2/core-classes/collection/mcreate-or-replace-document/snippets/mcreate-or-replace-document-1.java +++ /dev/null @@ -1,25 +0,0 @@ - -Document firstDocument = new Document(collection, "doc1"); -firstDocument.setContent("title", "foo"); -firstDocument.setContent("content", "bar"); - -Document secondDocument = new Document(collection, "doc2"); -secondDocument.setContent("title", "foo"); -secondDocument.setContent("content", "bar"); - -Document[] documents = new Document[]{firstDocument, secondDocument}; - -kuzzle - .collection("collection", "index") - .mCreateOrReplaceDocument(documents, new ResponseListener() { - @Override - public void onSuccess(JSONObject object) { - // callback called once the mCreateOrReplace operation has completed - // => the result is a JSON object containing the raw Kuzzle response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/mdelete-document/index.md b/doc/2/core-classes/collection/mdelete-document/index.md deleted file mode 100644 index 97e008fe..00000000 --- a/doc/2/core-classes/collection/mdelete-document/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -code: true -type: page -title: mdeleteDocument -description: Collection:mdeleteDocument ---- - -# mDeleteDocument - -Delete multiple [Documents](/sdk/java/2/core-classes/document) according to the input IDs. - ---- - -## mDeleteDocument(documentIds, [options], callback) - -| Arguments | Type | Description | -| ------------- | ----------- | ----------------------------------- | -| `documentIds` | String[] | Array of IDs of documents to delete | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. -Can return a 206 partial error in cases where some documents could not be deleted. - -## Usage - -<<< ./snippets/mdelete-document-1.java - -> Callback response: - -```json -["doc1", "doc2"] -``` diff --git a/doc/2/core-classes/collection/mdelete-document/snippets/mdelete-document-1.java b/doc/2/core-classes/collection/mdelete-document/snippets/mdelete-document-1.java deleted file mode 100644 index 2a853bb3..00000000 --- a/doc/2/core-classes/collection/mdelete-document/snippets/mdelete-document-1.java +++ /dev/null @@ -1,17 +0,0 @@ - -String[] documentIds = new String[]{"doc1", "doc2"}; - -kuzzle - .collection("collection", "index") - .mDeleteDocument(documentIds, new ResponseListener() { - @Override - public void onSuccess(JSONObject object) { - // callback called once the mDelete operation has completed - // => the result is a JSON object containing the raw Kuzzle response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/mget-document/index.md b/doc/2/core-classes/collection/mget-document/index.md deleted file mode 100644 index 83478d0d..00000000 --- a/doc/2/core-classes/collection/mget-document/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: mgetDocument -description: Collection:mgetDocument ---- - -# mGetDocument - -Get multiple [Documents](/sdk/java/2/core-classes/document) according to the input document IDs. - ---- - -## mGetDocument(documentIds, [options], callback) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------- | -| `documentIds` | String[] | Array of IDs of documents to retrieve | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. - -## Usage - -<<< ./snippets/mget-document-1.java - -> Callback response: - -```json -{ - "hits": [ - { "_id": "doc1", "first": "document" }, - { "_id": "doc2", "second": "document" } - ], - "total": 2 -} -``` diff --git a/doc/2/core-classes/collection/mget-document/snippets/mget-document-1.java b/doc/2/core-classes/collection/mget-document/snippets/mget-document-1.java deleted file mode 100644 index 78ade1d5..00000000 --- a/doc/2/core-classes/collection/mget-document/snippets/mget-document-1.java +++ /dev/null @@ -1,17 +0,0 @@ - -String[] documentIds = new String[]{"doc1", "doc2"}; - -kuzzle - .collection("collection", "index") - .mGetDocument(documentIds, new ResponseListener() { - @Override - public void onSuccess(JSONObject object) { - // callback called once the mGet operation has completed - // => the result is a JSON object containing the raw Kuzzle response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/mreplace-document/index.md b/doc/2/core-classes/collection/mreplace-document/index.md deleted file mode 100644 index c0718309..00000000 --- a/doc/2/core-classes/collection/mreplace-document/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: mreplaceDocument -description: Collection:mreplaceDocument ---- - -# mReplaceDocument - -Replace the provided [Documents](/sdk/java/2/core-classes/document). - ---- - -## mReplaceDocument(documents, [options], [callback]) - -| Arguments | Type | Description | -| ----------- | ----------- | -------------------------------------------------------------------- | -| `documents` | Document[] | Array of [Document](/sdk/java/2/core-classes/document) to replace | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. -Can return a 206 partial error in cases where documents could not be replaced. - -## Usage - -<<< ./snippets/mreplace-document-1.java - -> Callback response: - -```json -{ - "hits": [{ "first": "document" }, { "second": "document" }], - "total": 2 -} -``` diff --git a/doc/2/core-classes/collection/mreplace-document/snippets/mreplace-document-1.java b/doc/2/core-classes/collection/mreplace-document/snippets/mreplace-document-1.java deleted file mode 100644 index c299a099..00000000 --- a/doc/2/core-classes/collection/mreplace-document/snippets/mreplace-document-1.java +++ /dev/null @@ -1,25 +0,0 @@ - -Document firstDocument = new Document(collection, "doc1"); -firstDocument.setContent("title", "foo"); -firstDocument.setContent("content", "bar"); - -Document secondDocument = new Document(collection, "doc2"); -secondDocument.setContent("title", "foo"); -secondDocument.setContent("content", "bar"); - -Document[] documents = new Document[]{firstDocument, secondDocument}; - -kuzzle - .collection("collection", "index") - .mReplaceDocument(documents, new ResponseListener() { - @Override - public void onSuccess(JSONObject object) { - // callback called once the mReplace operation has completed - // => the result is a JSON object containing the raw Kuzzle response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/mupdate-document/index.md b/doc/2/core-classes/collection/mupdate-document/index.md deleted file mode 100644 index de8a8669..00000000 --- a/doc/2/core-classes/collection/mupdate-document/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: mupdateDocument -description: Collection:mupdateDocument ---- - -# mUpdateDocument - -Update the provided [Documents](/sdk/java/2/core-classes/document). - ---- - -## mUpdateDocument(documents, [options], [callback]) - -| Arguments | Type | Description | -| ----------- | ----------- | -------------------------------------------------------------------- | -| `documents` | Document[] | Array of [Documents](/sdk/java/2/core-classes/document) to update | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. -Can return a 206 partial error in cases where documents could not be updated. - -## Usage - -<<< ./snippets/mupdate-document-1.java - -> Callback response: - -```json -{ - "hits": [{ "first": "document" }, { "second": "document" }], - "total": 2 -} -``` diff --git a/doc/2/core-classes/collection/mupdate-document/snippets/mupdate-document-1.java b/doc/2/core-classes/collection/mupdate-document/snippets/mupdate-document-1.java deleted file mode 100644 index 9ff2e2a8..00000000 --- a/doc/2/core-classes/collection/mupdate-document/snippets/mupdate-document-1.java +++ /dev/null @@ -1,25 +0,0 @@ - -Document firstDocument = new Document(collection, "doc1"); -firstDocument.setContent("title", "foo"); -firstDocument.setContent("content", "bar"); - -Document secondDocument = new Document(collection, "doc2"); -secondDocument.setContent("title", "foo"); -secondDocument.setContent("content", "bar"); - -Document[] documents = new Document[]{firstDocument, secondDocument}; - -kuzzle - .collection("collection", "index") - .mUpdateDocument(documents, new ResponseListener() { - @Override - public void onSuccess(JSONObject object) { - // callback called once the mUpdate operation has completed - // => the result is a JSON object containing the raw Kuzzle response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/publish-message/index.md b/doc/2/core-classes/collection/publish-message/index.md deleted file mode 100644 index 83c2aef7..00000000 --- a/doc/2/core-classes/collection/publish-message/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: publishMessage -description: Collection:publishMessage ---- - -# publishMessage - -Publish a real-time message. - ---- - -## publishMessage(Document, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------- | -| `Document` | object | [Document](/sdk/java/2/core-classes/document) object | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## publishMessage(content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------- | -| `content` | JSON Object | Content of the document to publish | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ----------- | ------------------------------------------------------------- | ------- | -| `volatile` | JSON Object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns a raw Kuzzle response in JSON format. - -## Usage - -<<< ./snippets/publish-message-1.java diff --git a/doc/2/core-classes/collection/publish-message/snippets/publish-message-1.java b/doc/2/core-classes/collection/publish-message/snippets/publish-message-1.java deleted file mode 100644 index e1d5b31b..00000000 --- a/doc/2/core-classes/collection/publish-message/snippets/publish-message-1.java +++ /dev/null @@ -1,8 +0,0 @@ - -JSONObject message = new JSONObject().put("some", "content"); -JSONObject volatile = new JSONObject().put("volatile", "are volatile information"); -Options opts = new Options().setVolatile(volatile); - -kuzzle - .collection("collection", "index") - .publishMessage(message, opts); diff --git a/doc/2/core-classes/collection/replace-document/index.md b/doc/2/core-classes/collection/replace-document/index.md deleted file mode 100644 index 3d066207..00000000 --- a/doc/2/core-classes/collection/replace-document/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: replaceDocument -description: Collection:replaceDocument ---- - -# replaceDocument - -Replace an existing document and return the updated version as a [Document](/sdk/java/2/core-classes/document) object. - ---- - -## replaceDocument(documentId, content, [options], [callback]) - -| Arguments | Type | Description | -| ------------ | ----------- | --------------------------------- | -| `documentId` | string | Unique document identifier | -| `content` | JSON Object | Content of the document to create | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `volatile` | JSON Object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns an updated [Document](/sdk/java/2/core-classes/document) object. - -## Usage - -<<< ./snippets/replace-document-1.java diff --git a/doc/2/core-classes/collection/replace-document/snippets/replace-document-1.java b/doc/2/core-classes/collection/replace-document/snippets/replace-document-1.java deleted file mode 100644 index 9c2c57ce..00000000 --- a/doc/2/core-classes/collection/replace-document/snippets/replace-document-1.java +++ /dev/null @@ -1,16 +0,0 @@ - -JSONObject newContent = new JSONObject("new", "document content"); - -kuzzle - .collection("collection", "index") - .replaceDocument("documentId", newContent, new ResponseListener() { - @Override - public void onSuccess(Document document) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/collection/room/index.md b/doc/2/core-classes/collection/room/index.md deleted file mode 100644 index 16490bf6..00000000 --- a/doc/2/core-classes/collection/room/index.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -code: true -type: page -title: room -description: Collection:room ---- - -# room - -Creates a new [Room](/sdk/java/2/core-classes/room) object, using its constructor. - ---- - -## room([options]) - -| Arguments | Type | Description | -| --------- | ------ | -------------------------- | -| `options` | object | Subscription configuration | - -## Options - -Provided options are passed directly to the [Room](/sdk/java/2/core-classes/room) object constructor. - ---- - -## Return Value - -Returns the newly created [Room](/sdk/java/2/core-classes/room) object. - -## Usage - -<<< ./snippets/room-1.java diff --git a/doc/2/core-classes/collection/room/snippets/room-1.java b/doc/2/core-classes/collection/room/snippets/room-1.java deleted file mode 100644 index 2cd5aeb1..00000000 --- a/doc/2/core-classes/collection/room/snippets/room-1.java +++ /dev/null @@ -1,23 +0,0 @@ - -JSONObject filters = new JSONObject() - .put("in", - new JSONObject("field") - .put(new JSONArray() - .put("some") - .put("filter") - ) - ); - -Room room = kuzzle.collection("collection", "index") - .room() - .renew(filters, new ResponseListener() { - @Override - public void onSuccess(NotificationResponse object) { - // handle notifications - } - - @Override - public void onError(JSONObject error) { - // Handle notifications error - } - }); diff --git a/doc/2/core-classes/collection/scroll-specifications/index.md b/doc/2/core-classes/collection/scroll-specifications/index.md deleted file mode 100644 index 436785ed..00000000 --- a/doc/2/core-classes/collection/scroll-specifications/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -code: true -type: page -title: scrollSpecifications -description: Collection:scrollSpecifications ---- - -# scrollSpecifications - -Returns a JSON object containing the next page of the scroll session, and the `scrollId` to be used in the next `scroll` action. -A scroll session is always initiated by a `searchSpecification` action with the `scroll` argument. - ---- - -## scrollSpecifications(scrollId, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------- | -| `scrollId` | string | The "scrollId" provided with the last scrollSpecifications response or from the initial searchSpecifications request | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `scroll` | string | Re-initializes the scroll session timeout to its value. If not defined, the scroll timeout is defaulted to a Kuzzle configuration | `undefined` | - -## Usage - -<<< ./snippets/scroll-specifications-1.java - -> Callback response - -```json -{ - "hits": [{ "first": "specification" }, { "second": "specification" }], - "total": 2 -} -``` diff --git a/doc/2/core-classes/collection/scroll-specifications/snippets/scroll-specifications-1.java b/doc/2/core-classes/collection/scroll-specifications/snippets/scroll-specifications-1.java deleted file mode 100644 index 8bb8301a..00000000 --- a/doc/2/core-classes/collection/scroll-specifications/snippets/scroll-specifications-1.java +++ /dev/null @@ -1,21 +0,0 @@ - -Options opts = new Options(); -opts.setScroll("1m"); - -kuzzle - .collection("collection", "index") - .scrollSpecifications(scrollId, opts, new ResponseListener() { - @Override - public void onSuccess(JSONObject res) { - for (int i = 0; i < res.getJSONArray("hits").length(); i++) { - res.getJSONArray("hits").getJSONObject(i) // Specification - } - - res.getString("total"); // Total specifications count - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/scroll/index.md b/doc/2/core-classes/collection/scroll/index.md deleted file mode 100644 index 61c3819c..00000000 --- a/doc/2/core-classes/collection/scroll/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: scroll -description: Collection:scroll ---- - -# scroll - -Returns a [SearchResult](/sdk/java/2/core-classes/search-result) object containing the next page of the scroll session, and the `scrollId` to be used in the next `scroll` action. -A scroll session is always initiated by a `search` action and including the `scroll` argument; more information below. - -:::info -There is a small delay between the time a document is created and its availability in our search layer (usually a couple of seconds). That means that a document that was just created might not be returned immediately by this function. -::: - -:::info -To get more information about scroll sessions, please refer to the [API reference documentation](/core/1/api/controllers/document/search). -::: - ---- - -## scroll(scrollId, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------- | -| `scrollId` | string | The "scrollId" provided with the last scroll response or from the initial search request if it is the first scroll call | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `scroll` | string | Re-initializes the scroll session timeout to its value. If not defined, the scroll timeout is defaulted to a Kuzzle configuration | `undefined` | - ---- - -## Callback Response - -Returns an instantiated [SearchResult](/sdk/java/2/core-classes/search-result) object. - ---- - -## Usage - -<<< ./snippets/scroll-1.java diff --git a/doc/2/core-classes/collection/scroll/snippets/scroll-1.java b/doc/2/core-classes/collection/scroll/snippets/scroll-1.java deleted file mode 100644 index 1c94a896..00000000 --- a/doc/2/core-classes/collection/scroll/snippets/scroll-1.java +++ /dev/null @@ -1,23 +0,0 @@ - -Options opts = new Options(); -opts.setScroll("1m"); - -kuzzle - .collection("collection", "index") - .scroll(scrollId, opts, new ResponseListener() { - @Override - public void onSuccess(SearchResult searchResult) { - for (Document doc : searchResult.getDocuments()) { - // Get documents - } - - searchResult.getTotal(); // return total of documents returned - - searchResult.getAggregations(): // return a JSONObject representing the aggregations response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/search-specifications/index.md b/doc/2/core-classes/collection/search-specifications/index.md deleted file mode 100644 index 15242569..00000000 --- a/doc/2/core-classes/collection/search-specifications/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -code: true -type: page -title: searchSpecifications -description: Collection:searchSpecifications ---- - -# searchSpecifications - -Retrieves every specifications across indexes/collections according to the given filters. - ---- - -## searchSpecifications(filters, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `filters` | JSON object | Search request body, using [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/5.x/search-request-body.html) format.
If given an empty object, matches all specifications across index/collections | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `from` | number | Provide the starting offset of the request (used to paginate results) | `0` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `scroll` | string | Start a scroll session, with a time to live equals to this parameter's value following the [Elastisearch time format](https://www.elastic.co/guide/en/elasticsearch/reference/5.0/common-options.html#time-units) | `undefined` | -| `size` | number | Provide the maximum number of results of the request (used to paginate results) | `10` | - -## Usage - -<<< ./snippets/search-specifications-1.java - -> Callback response - -```json -{ - "hits": [{ "first": "specification" }, { "second": "specification" }], - "total": 2, - "scrollId": "foobar" -} -``` diff --git a/doc/2/core-classes/collection/search-specifications/snippets/search-specifications-1.java b/doc/2/core-classes/collection/search-specifications/snippets/search-specifications-1.java deleted file mode 100644 index 516f9840..00000000 --- a/doc/2/core-classes/collection/search-specifications/snippets/search-specifications-1.java +++ /dev/null @@ -1,32 +0,0 @@ - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; - -Kuzzle kuzzle = new Kuzzle("localhost"); - -JSONObject filters = new JSONObject() - .put("match_all", new JSONObject() - .put("boost", 1) - ); - -Options options = new Options(); -options.setFrom((long) 0); -options.setSize((long) 20); - -kuzzle - .collection("collection", "index") - .searchSpecifications(filters, options, new ResponseListener() { - @Override - public void onSuccess(JSONObject res) { - for (int i = 0; i < res.getJSONArray("hits").length(); i++) { - res.getJSONArray("hits").getJSONObject(i) // Specification - } - - res.getString("total"); // Total specifications count - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/search/index.md b/doc/2/core-classes/collection/search/index.md deleted file mode 100644 index b0a1fb7f..00000000 --- a/doc/2/core-classes/collection/search/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -code: true -type: page -title: search -description: Collection:search ---- - -# search - -Executes a search on the collection. - -:::info -There is a small delay between the time a document is created and its availability in our search layer (usually a couple of seconds). That means that a document that was just created might not be returned immediately by this function. -::: - -## Processing large data sets - -When processing a large number of documents (i.e. more than 1000), using `search` is not always the best option. - -Pagination of results can be done by using the from and size but the cost becomes prohibitive when deep pagination is reached. In fact, Elasticsearch, Kuzzle's embedded database, limits results to 10,000 records by default. - -Instead, the recommended way to process a large number of documents is to use [`Collection.scroll`](/sdk/java/2/core-classes/collection/scroll) or, easier, [`SearchResult.fetchNext`](/sdk/java/2/core-classes/search-result/fetch-next). - -See [`SearchResult.fetchNext`](/sdk/java/2/core-classes/search-result/fetch-next#how-to-process-every-document-of-a-collection) for an example of how to process every document of a collection. - ---- - -## search(body, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `body` | JSON object | Search request body, using [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/5.x/search-request-body.html) format.
If given an empty object, matches all documents in the collection | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `from` | number | Provide the starting offset of the request (used to paginate results) | `0` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `scroll` | string | Start a scroll session, with a time to live equals to this parameter's value following the [Elastisearch time format](https://www.elastic.co/guide/en/elasticsearch/reference/5.0/common-options.html#time-units) | `undefined` | -| `size` | number | Provide the maximum number of results of the request (used to paginate results) | `10` | - -:::info -To get more information about scroll sessions, please refer to the [API reference documentation](/core/1/api/controllers/document/search). -::: - ---- - -## Callback Response - -Returns an instance of [SearchResult](/sdk/java/2/core-classes/search-result). - -## Usage - -<<< ./snippets/search-1.java diff --git a/doc/2/core-classes/collection/search/snippets/search-1.java b/doc/2/core-classes/collection/search/snippets/search-1.java deleted file mode 100644 index 6dde89e8..00000000 --- a/doc/2/core-classes/collection/search/snippets/search-1.java +++ /dev/null @@ -1,87 +0,0 @@ - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; - -Kuzzle kuzzle = new Kuzzle("localhost"); - -JSONObject body = new JSONObject() - .put("query", new JSONObject() - .put("bool", new JSONObject() - .put("must", new JSONArray() - .put( - new JSONObject().put("terms", - new JSONObject().put("status", - new JSONArray() - .put("idle") - .put("wantToHire") - .put("toHire") - .put("riding") - ) - ) - ) - .put( - new JSONObject().put("term", - new JSONObject() - .put("type", new JSONArray().put("cab")) - ) - ) - .put( - new JSONObject().put("geoDistance", - new JSONObject() - .put("distance", "10km") - .put("pos", - new JSONObject() - .put("lat", "48.8566140") - .put("lon", "2.352222") - ) - ) - ) - ) - ) - ) - .put("sort", new JSONArray() - .put("status") - .put(new JSONObject() - .put("_geoDistance", new JSONObject() - .put("pos", new JSONObject() - .put("lat", "48.8566140") - .put("lon", "2.352222") - ) - .put('order'; "asc") - ) - ) - .put(new JSONObject() - .put("date", "desc") - ) - ) - .put("aggregations", new JSONObject() - .put("aggs_name", new JSONObject() - .put("terms", new JSONObject() - .put("field", "field_name") - ) - ) - ); - -Options options = new Options(); -options.setFrom((long) 0); -options.setSize((long) 20); - -kuzzle - .collection("collection", "index") - .search(body, options, new ResponseListener() { - @Override - public void onSuccess(SearchResult searchResult) { - for (Document doc : searchResult.getDocuments()) { - // Get documents - } - - searchResult.getTotal(); // return total of documents returned - - searchResult.getAggregations(): // return a JSONObject representing the aggregations response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/set-headers/index.md b/doc/2/core-classes/collection/set-headers/index.md deleted file mode 100644 index f22fc285..00000000 --- a/doc/2/core-classes/collection/set-headers/index.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -code: true -type: page -title: setHeaders -description: Collection:setHeaders ---- - -# setHeaders - -This is a helper function returning itself, allowing to easily set headers while chaining calls. - ---- - -## setHeaders(content, [replace]) - -| Arguments | Type | Description | -| --------- | ----------- | ------------------------------------------------------------------------- | -| `content` | JSON Object | New content | -| `replace` | boolean | true: replace the current content with the provided data, false: merge it | - -**Note:** by default, the `replace` argument is set to `false` - ---- - -## Return value - -Returns the `Collection` object to allow chaining. - -## Usage - -<<< ./snippets/set-headers-1.java diff --git a/doc/2/core-classes/collection/set-headers/snippets/set-headers-1.java b/doc/2/core-classes/collection/set-headers/snippets/set-headers-1.java deleted file mode 100644 index 2dd625fb..00000000 --- a/doc/2/core-classes/collection/set-headers/snippets/set-headers-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -JSONObject headers = new JSONObject() - .put("someContent", "someValue") - .put("volatile", new JSONObject() - .put("someVolatileData", new JSONArray() - .put("with") - .put("some") - .put("values") - ) - ); - -kuzzle - .collection("collection", "index") - .setHeaders(content, true); diff --git a/doc/2/core-classes/collection/subscribe/index.md b/doc/2/core-classes/collection/subscribe/index.md deleted file mode 100644 index 4de9b718..00000000 --- a/doc/2/core-classes/collection/subscribe/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: subscribe -description: Collection:subscribe ---- - -# subscribe - -Subscribes to this collection with a set of filters. - -The provided callback will be called everytime a [notification](/sdk/java/2/essentials/realtime-notifications) is received from Kuzzle. - ---- - -## subscribe(filters, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------------------------------------------- | -| `filters` | JSON Object | [Koncorde Filters](/core/1/guides/cookbooks/realtime-api) | -| `options` | object | (Optional) Subscription configuration. Passed to the Room constructor. | -| `callback` | function | Callback to call every time a notification is received on this subscription | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `volatile` | JSON Object | Additional information passed to notifications to other users | `null` | -| `scope` | string | Filter document notifications depending on their scope status. You may receive entering documents (scope: `in`), leaving documents (scope: `out`), all documents changes (scope: `all`) or filter these notifications completely (scope: `none`). This filter does not affect pub/sub messages or user events. | `all` | -| `state` | string | Filter document notifications depending on the state of the modifying request. You may receive real-time notifications when a document is about to be changed (state: `pending`), or be notified when the change has been fully written in the database (state: `done`), or both (state: `all`). This filter does not affect pub/sub messages or user events. | `done` | -| `subscribeToSelf` | boolean | (Don't) subscribe to notifications fired as a consequence of our own queries | `true` | -| `users` | string | Filter notifications fired upon a user entering the room (user: `in`), leaving the room (user: `out`), or both (user: `all`). Setting this variable to `none` prevents receiving these notifications | `none` | - -The `options` object is directly passed to the Room constructor. -See the [Room object](/sdk/java/2/core-classes/room) documentation for more information about these options and notifications. - ---- - -## Return Value - -Returns an object exposing the following method: - `onDone(callback)` - -The `callback` argument is called when the subscription ends, either successfully or with an error. - -## Usage - -<<< ./snippets/subscribe-1.java diff --git a/doc/2/core-classes/collection/subscribe/snippets/subscribe-1.java b/doc/2/core-classes/collection/subscribe/snippets/subscribe-1.java deleted file mode 100644 index 51566654..00000000 --- a/doc/2/core-classes/collection/subscribe/snippets/subscribe-1.java +++ /dev/null @@ -1,60 +0,0 @@ - -JSONObject filter = new JSONObject() - .put("and", new JSONArray() - .put( - new JSONObject().put("in", - new JSONObject().put("status", - new JSONArray() - .put("idle") - .put("wantToHire") - .put("toHire") - .put("riding") - ) - ) - ) - .put( - new JSONObject().put("in", - new JSONObject() - .put("type", new JSONArray().put("cab")) - ) - ) - .put( - new JSONObject().put("geoDistance", - new JSONObject() - .put("distance", "10km") - .put("pos", - new JSONObject() - .put("lat", "48.8566140") - .put("lon", "2.352222") - ) - ) - ) - ); - -kuzzle - .collection("collection", "index") - .subscribe(filter, new ResponseListener() { - @Override - public void onSuccess(NotificationResponse object) { - // called each time a new notification on this filter is received - - // check the Room/Notifications section of this documentation - // to get notification examples - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }) - .onDone(new ResponseListener() { - @Override - public void onSuccess(Room response) { - // Handle subscription success - } - - @Override - public void onError(JSONObject error) { - // Handle subscription error - } - }); diff --git a/doc/2/core-classes/collection/truncate/index.md b/doc/2/core-classes/collection/truncate/index.md deleted file mode 100644 index f828a090..00000000 --- a/doc/2/core-classes/collection/truncate/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -code: true -type: page -title: truncate -description: Collection:truncate ---- - -# truncate - -Truncate the collection, removing all stored documents but keeping all associated mappings. - -This method is a lot faster than removing all documents using multiple delete requests. - ---- - -## truncate([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. - -## Usage - -<<< ./snippets/truncate-1.java - -> Callback response: - -```json -{ - "status": 200, - "error": null, - "requestId": "8fdc0efb-6fc7-427d-a3a1-fd8cf5eabc20", - "controller": "admin", - "action": "truncateCollection", - "collection": "name of the truncated collection", - "index": "name of the index containing the truncated collection", - "volatile": {}, - "state": "done", - "result": { "acknowledged": true } -} -``` diff --git a/doc/2/core-classes/collection/truncate/snippets/truncate-1.java b/doc/2/core-classes/collection/truncate/snippets/truncate-1.java deleted file mode 100644 index 610dee52..00000000 --- a/doc/2/core-classes/collection/truncate/snippets/truncate-1.java +++ /dev/null @@ -1,15 +0,0 @@ - -kuzzle - .collection("collection", "index") - .truncate(new ResponseListener() { - @Override - public void onSuccess(JSONObject object) { - // callback called once the truncate operation has completed - // => the result is a JSON object containing the raw Kuzzle response - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/update-document/index.md b/doc/2/core-classes/collection/update-document/index.md deleted file mode 100644 index ce1f11af..00000000 --- a/doc/2/core-classes/collection/update-document/index.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -code: true -type: page -title: updateDocument -description: Collection:updateDocument ---- - -# updateDocument - -Update parts of a document, by replacing some fields or adding new ones. -Note that you cannot remove fields this way: missing fields will simply be left unchanged. - ---- - -## updateDocument(documentId, content, [options], [callback]) - -| Arguments | Type | Description | -| ------------ | ----------- | --------------------------------- | -| `documentId` | string | Unique document identifier | -| `content` | JSON object | Content of the document to create | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `volatile` | JSON object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | -| `retryOnConflict` | int | Number of retries to attempt before rejecting this update because of a cluster sync conflict | `0` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - ---- - -## Callback Response - -Returns an up-to-date [Document](/sdk/java/2/core-classes/document) object. - -## Usage - -<<< ./snippets/update-document-1.java diff --git a/doc/2/core-classes/collection/update-document/snippets/update-document-1.java b/doc/2/core-classes/collection/update-document/snippets/update-document-1.java deleted file mode 100644 index 35782bfb..00000000 --- a/doc/2/core-classes/collection/update-document/snippets/update-document-1.java +++ /dev/null @@ -1,16 +0,0 @@ - -JSONObject newTitle = new JSONObject().put("title", "a shiny new title"); - -kuzzle - .collection("collection", "index") - .updateDocument("documentId", newTitle, new ResponseListener() { - @Override - public void onSuccess(Document result) { - // result is an updated Document object - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/update-specifications/index.md b/doc/2/core-classes/collection/update-specifications/index.md deleted file mode 100644 index 2e352526..00000000 --- a/doc/2/core-classes/collection/update-specifications/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -code: true -type: page -title: updateSpecifications -description: Collection:updateSpecifications ---- - -# updateSpecifications - -Update parts of a specification, by replacing some fields or adding new ones. -Note that you cannot remove fields this way: missing fields will simply be left unchanged. - ---- - -## updateSpecifications(content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------- | -| `content` | JSON object | Content of the specification to update | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | -| `retryOnConflict` | int | Number of retries to attempt before rejecting this update because of a cluster sync conflict | `0` | - ---- - -## Return Value - -Returns the `Collection` object to allow chaining. - -## Usage - -<<< ./snippets/update-specifications-1.java - -> Callback response - -```json -{ - "index": { - "collection": { - "strict": "true", - "fields": { - "foo": { - "mandatory": "true", - "type": "string", - "defaultValue": "bar" - } - } - } - } -} -``` diff --git a/doc/2/core-classes/collection/update-specifications/snippets/update-specifications-1.java b/doc/2/core-classes/collection/update-specifications/snippets/update-specifications-1.java deleted file mode 100644 index e3b32e80..00000000 --- a/doc/2/core-classes/collection/update-specifications/snippets/update-specifications-1.java +++ /dev/null @@ -1,26 +0,0 @@ - -JSONObject fooField = new JSONObject() - .put("mandatory", "true") - .put("type", "string") - .put("defaultValue", "bar"); - -JSONObject fields = new JSONObject() - .put("foo", fooField); - -JSONObject specifications = new JSONObject() - .put("strict", "true") - .put("fields", fields); - -kuzzle - .collection("collection", "index") - .updateSpecifications(specifications, new ResponseListener() { - @Override - public void onSuccess(JSONObject res) { - // result is a JSONObject - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/collection/validate-specifications/index.md b/doc/2/core-classes/collection/validate-specifications/index.md deleted file mode 100644 index 6391b73c..00000000 --- a/doc/2/core-classes/collection/validate-specifications/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -code: true -type: page -title: validateSpecifications -description: Collection:validateSpecifications ---- - -# validateSpecifications - -Validate a specification. - ---- - -## validateSpecifications(content, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------------- | -| `content` | JSON object | Content of the specification to validate | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a boolean indicating whether or not the input specifications is valid or not. - -## Usage - -<<< ./snippets/validate-specifications-1.java diff --git a/doc/2/core-classes/collection/validate-specifications/snippets/validate-specifications-1.java b/doc/2/core-classes/collection/validate-specifications/snippets/validate-specifications-1.java deleted file mode 100644 index cae3e309..00000000 --- a/doc/2/core-classes/collection/validate-specifications/snippets/validate-specifications-1.java +++ /dev/null @@ -1,26 +0,0 @@ - -JSONObject fooField = new JSONObject() - .put("mandatory", "true") - .put("type", "string") - .put("defaultValue", "bar"); - -JSONObject fields = new JSONObject() - .put("foo", fooField); - -JSONObject specifications = new JSONObject() - .put("strict", "true") - .put("fields", fields); - -kuzzle - .collection("collection", "index") - .validateSpecifications(specifications, new ResponseListener() { - @Override - public void onSuccess(Boolean isValid) { - // isValid is a boolean - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/document/constructor/index.md b/doc/2/core-classes/document/constructor/index.md deleted file mode 100644 index 53133737..00000000 --- a/doc/2/core-classes/document/constructor/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: constructor -description: Document:constructor -order: 1 ---- - -# Document - -Kuzzle handles two types of documents: realtime messages and stored documents. Document is the object representation of one of these document types. - ---- - -## Document(Collection, [documentId], [content]) - -| Arguments | Type | Description | -| ------------ | ----------- | --------------------------------------------------- | -| `Collection` | object | An instantiated Collection object | -| `content` | JSON Object | Initializes this document with the provided content | -| `documentId` | string | ID of an existing document. | - -**Note:** this constructor won't make any call to Kuzzle. When providing only a document ID, the `refresh` method should be called to retrieve the corresponding document content. - ---- - -## Properties - -| Property name | Type | Description | get/set | -| ------------- | ----------- | ----------------------------------------------- | ------- | -| `collection` | string | The collection associated to this document | get | -| `content` | JSON Object | The content of the document | get/set | -| `headers` | JSON Object | Common headers for all sent documents. | get/set | -| `id` | string | Unique document identifier | get/set | -| `meta` | JSON Object | Document metadata | get | -| `version` | integer | Current document version | get | - -**Notes:** - -- setting a new value to the `content` property is equivalent to calling `setContent(data, false)` -- setting a new value to the `id` property will force this value for this document -- the `headers` property is inherited from the provided `Collection` object and can be overrided - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/document/constructor/snippets/constructor-1.java b/doc/2/core-classes/document/constructor/snippets/constructor-1.java deleted file mode 100644 index 201adaf0..00000000 --- a/doc/2/core-classes/document/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,10 +0,0 @@ - -Document document = new Document(collection); - -Document document = new Document(collection, "id"); - -JSONObject content = new JSONObject(); -content.put("content", "some content"); -Document document = new Document(collection, content); - -Document document = new Document(collection, "id", content); diff --git a/doc/2/core-classes/document/delete/index.md b/doc/2/core-classes/document/delete/index.md deleted file mode 100644 index 8972d033..00000000 --- a/doc/2/core-classes/document/delete/index.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -code: true -type: page -title: delete -description: Document:delete ---- - -# delete - -Deletes this document in Kuzzle. - ---- - -## delete([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `volatile` | JSON Object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Callback Response - -Returns a string containing the ID of the deleted document. - -## Usage - -<<< ./snippets/delete-1.java diff --git a/doc/2/core-classes/document/delete/snippets/delete-1.java b/doc/2/core-classes/document/delete/snippets/delete-1.java deleted file mode 100644 index f7ba4b63..00000000 --- a/doc/2/core-classes/document/delete/snippets/delete-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -document.delete(new ResponseListener() { - @Override - public void onSuccess(Document object) { - // called once the delete action has been completed - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/document/exists/index.md b/doc/2/core-classes/document/exists/index.md deleted file mode 100644 index 02d80deb..00000000 --- a/doc/2/core-classes/document/exists/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: exists -description: Document:exists ---- - -# exists - -Checks if the document exists in Kuzzle. - ---- - -## exists([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Return a boolean indicating whether or not the document exists in Kuzzle. - -## Usage - -<<< ./snippets/exists-1.java diff --git a/doc/2/core-classes/document/exists/snippets/exists-1.java b/doc/2/core-classes/document/exists/snippets/exists-1.java deleted file mode 100644 index 01de2360..00000000 --- a/doc/2/core-classes/document/exists/snippets/exists-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -document.exists(new ResponseListener() { - @Override - public void onSuccess(Boolean exists) { - // called once the exists check has been completed - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/document/index.md b/doc/2/core-classes/document/index.md deleted file mode 100644 index ad9a6cc9..00000000 --- a/doc/2/core-classes/document/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: Document -description: Document documentation ---- diff --git a/doc/2/core-classes/document/publish/index.md b/doc/2/core-classes/document/publish/index.md deleted file mode 100644 index 064d023d..00000000 --- a/doc/2/core-classes/document/publish/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: publish -description: Document:publish ---- - -# publish - -Publishes the content of this document as a real-time message. - ---- - -## publish([options]) - -| Arguments | Type | Description | -| --------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ----------- | ------------------------------------------------------------- | ------- | -| `volatile` | JSON Object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns this `Document` object to allow chaining. - -## Usage - -<<< ./snippets/publish-1.java diff --git a/doc/2/core-classes/document/publish/snippets/publish-1.java b/doc/2/core-classes/document/publish/snippets/publish-1.java deleted file mode 100644 index b671526e..00000000 --- a/doc/2/core-classes/document/publish/snippets/publish-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -document.publish(); diff --git a/doc/2/core-classes/document/refresh/index.md b/doc/2/core-classes/document/refresh/index.md deleted file mode 100644 index a9864524..00000000 --- a/doc/2/core-classes/document/refresh/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: refresh -description: Document:refresh ---- - -# refresh - -Creates a new `Document` object with the last version of this document stored in Kuzzle. - ---- - -## refresh([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Return a new `Document` object containing the last document version. - -## Usage - -<<< ./snippets/refresh-1.java diff --git a/doc/2/core-classes/document/refresh/snippets/refresh-1.java b/doc/2/core-classes/document/refresh/snippets/refresh-1.java deleted file mode 100644 index bd1b2eba..00000000 --- a/doc/2/core-classes/document/refresh/snippets/refresh-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -document.refresh(new ResponseListener() { - @Override - public void onSuccess(Document object) { - // called once the refresh action has been completed - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/document/save/index.md b/doc/2/core-classes/document/save/index.md deleted file mode 100644 index eaef20b1..00000000 --- a/doc/2/core-classes/document/save/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: save -description: Document:save ---- - -# save - -Saves this document into Kuzzle. - -If this is a new document, this function will create it in Kuzzle and the `id` property will be made available. -Otherwise, this method will replace the latest version of the document in Kuzzle with the content of this current object. - ---- - -## save([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `volatile` | JSON Object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns this `Document` object to allow chaining. - ---- - -## Callback Response - -Return this `Document` object once the document has been saved. - -## Usage - -<<< ./snippets/save-1.java diff --git a/doc/2/core-classes/document/save/snippets/save-1.java b/doc/2/core-classes/document/save/snippets/save-1.java deleted file mode 100644 index 6706d959..00000000 --- a/doc/2/core-classes/document/save/snippets/save-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -document.save(new ResponseListener() { - @Override - public void onSuccess(Document object) { - // called once the save action has been completed - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/document/set-content/index.md b/doc/2/core-classes/document/set-content/index.md deleted file mode 100644 index dee1b15e..00000000 --- a/doc/2/core-classes/document/set-content/index.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -code: true -type: page -title: setContent -description: Document:setContent ---- - -# setContent - -Replaces the current content with new data. -This is a helper function returning a reference to itself so that you can easily chain calls. - -:::info -Changes made by this function won't be applied until the `save` method is called -::: - ---- - -## setContent(data, [replace]) - -| Arguments | Type | Description | -| --------- | ----------- | ------------------------------------------------------------------------- | -| `data` | JSON Object | New content | -| `replace` | boolean | true: replace the current content with the provided data, false: merge it | - -**Note:** by default, the `replace` argument is set to `false` - ---- - -## Return Value - -Returns this `Document` object to allow chaining. - -## Usage - -<<< ./snippets/set-content-1.java diff --git a/doc/2/core-classes/document/set-content/snippets/set-content-1.java b/doc/2/core-classes/document/set-content/snippets/set-content-1.java deleted file mode 100644 index 024b2dbf..00000000 --- a/doc/2/core-classes/document/set-content/snippets/set-content-1.java +++ /dev/null @@ -1,4 +0,0 @@ - -JSONObject content = new JSONObject().put("content", "some content"); - -document.setContent(content, true); diff --git a/doc/2/core-classes/document/set-headers/index.md b/doc/2/core-classes/document/set-headers/index.md deleted file mode 100644 index 911d3ae8..00000000 --- a/doc/2/core-classes/document/set-headers/index.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -code: true -type: page -title: setHeaders -description: Document:setHeaders ---- - -# setHeaders - -This is a helper function returning itself, allowing to easily chain calls. - ---- - -## setHeaders(content, [replace]) - -| Arguments | Type | Description | -| --------- | ----------- | ------------------------------------------------------------------------- | -| `content` | JSON Object | New content | -| `replace` | boolean | true: replace the current content with the provided data, false: merge it | - -**Note:** by default, the `replace` argument is set to `false` - ---- - -## Return value - -Returns this `Document` object to allow chaining. - -## Usage - -<<< ./snippets/set-headers-1.java diff --git a/doc/2/core-classes/document/set-headers/snippets/set-headers-1.java b/doc/2/core-classes/document/set-headers/snippets/set-headers-1.java deleted file mode 100644 index 3651d23a..00000000 --- a/doc/2/core-classes/document/set-headers/snippets/set-headers-1.java +++ /dev/null @@ -1,4 +0,0 @@ - -JSONObject headers = new JSONObject().put("someContent", "someValue"); - -document.setHeaders(headers, true); diff --git a/doc/2/core-classes/document/subscribe/index.md b/doc/2/core-classes/document/subscribe/index.md deleted file mode 100644 index 40076ce1..00000000 --- a/doc/2/core-classes/document/subscribe/index.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -code: true -type: page -title: subscribe -description: Document:subscribe ---- - -# subscribe - -Listens to changes occuring in this document. -Throws an error if this document has not yet been created in Kuzzle. - -The provided callback will be called everytime a [notification](/sdk/java/2/essentials/realtime-notifications) is received from Kuzzle. - ---- - -## subscribe([options], callback) - -| Arguments | Type | Description | -| ---------- | -------- | ---------------------------------------------------------------------------------- | -| `options` | object | Subscription configuration | -| `callback` | function | Callback that will be called each time a change has been detected on this document | - ---- - -## Options - -Options are directly passed to the [Room](/sdk/java/2/core-classes/room) object constructor. - ---- - -## Return Value - -Returns an object exposing the following method: - `onDone(callback)` - -The `callback` argument is called when the subscription ends, either successfully or with an error. - -## Usage - -<<< ./snippets/subscribe-1.java diff --git a/doc/2/core-classes/document/subscribe/snippets/subscribe-1.java b/doc/2/core-classes/document/subscribe/snippets/subscribe-1.java deleted file mode 100644 index 3a563eef..00000000 --- a/doc/2/core-classes/document/subscribe/snippets/subscribe-1.java +++ /dev/null @@ -1,23 +0,0 @@ - -Room room = document.subscribe(new ResponseListener() { - @Override - public void onSuccess(NotificationResponse object) { - // called each time a change occurs on this document - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }) - .onDone(new ResponseListener() { - @Override - public void onSuccess(Room response) { - // Handle subscription success - } - - @Override - public void onError(JSONObject error) { - // Handle subscription error - } - }); diff --git a/doc/2/core-classes/index.md b/doc/2/core-classes/index.md deleted file mode 100644 index a4eb0e59..00000000 --- a/doc/2/core-classes/index.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -code: false -type: branch -order: 10 -title: Core classes -description: Core classes ---- diff --git a/doc/2/core-classes/kuzzle/add-listener/index.md b/doc/2/core-classes/kuzzle/add-listener/index.md deleted file mode 100644 index 4d50a1e2..00000000 --- a/doc/2/core-classes/kuzzle/add-listener/index.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -code: true -type: page -title: addListener -description: Kuzzle:addListener ---- - -# addListener - -Adds a listener to an event. When an event is fired, listeners are called in the order that they are added. - ---- - -## addListener(event, listener) - -| Arguments | Type | Description | -| ---------- | -------- | -------------------------------------------------------------------------------- | -| `event` | string | One of the event described in the `Event Handling` section of this documentation | -| `listener` | function | The function to call each time one of the registered event is fired | - ---- - -## Return Value - -Returns the `Kuzzle` object to allow chaining. - -## Usage - -<<< ./snippets/add-listener-1.java diff --git a/doc/2/core-classes/kuzzle/add-listener/snippets/add-listener-1.java b/doc/2/core-classes/kuzzle/add-listener/snippets/add-listener-1.java deleted file mode 100644 index 27e9f82a..00000000 --- a/doc/2/core-classes/kuzzle/add-listener/snippets/add-listener-1.java +++ /dev/null @@ -1,8 +0,0 @@ - -EventListener eventListener = new EventListener() { - @Override - public void trigger(Object... args) { - // Actions to perform when receiving a 'subscribed' global event - } -}; -kuzzle.addListener(Event.connected, eventListener); diff --git a/doc/2/core-classes/kuzzle/check-token/index.md b/doc/2/core-classes/kuzzle/check-token/index.md deleted file mode 100644 index 762879bd..00000000 --- a/doc/2/core-classes/kuzzle/check-token/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: checkToken -description: Kuzzle:checkToken ---- - -# checkToken - -> Callback response if the token is valid: - -```json -{ - "expiresAt": 1454588077399, - "valid": true -} -``` - -> Callback response if the token is invalid: - -```json -{ - "valid": false, - "state": "" -} -``` - -Checks the validity of a JSON Web Token. - -:::info -This method is non-queuable, meaning that during offline mode, it will be discarded and the callback return an error. -::: - ---- - -## checkToken(token, callback) - -| Arguments | Type | Description | -| ---------- | -------- | ------------------------------ | -| `token` | string | The token to check | -| `callback` | function | Callback handling the response | - -**Note:** this method sends an unauthenticated API call to Kuzzle, meaning it ignores the JWT Token property, even if it has been set. - ---- - -## Callback Response - -Returns a JSON object with a `valid` boolean property. -If the token is valid, an `expiresAt` property is set with the expiration timestamp. If not, a `state` property is set explaining why the token is invalid. - -## Usage - -<<< ./snippets/check-token-1.java diff --git a/doc/2/core-classes/kuzzle/check-token/snippets/check-token-1.java b/doc/2/core-classes/kuzzle/check-token/snippets/check-token-1.java deleted file mode 100644 index d296c4c3..00000000 --- a/doc/2/core-classes/kuzzle/check-token/snippets/check-token-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.checkToken("some jwt token", new ResponseListener() { - @Override - public void onSuccess(TokenValidity tokenInfo) { - if (tokenInfo.isValid()) { - // tokenInfo.getExpiresAt() returns the expiration timestamp - } - else { - // tokenInfo.getState() returns the invalidity reason - } - } -}); diff --git a/doc/2/core-classes/kuzzle/collection/index.md b/doc/2/core-classes/kuzzle/collection/index.md deleted file mode 100644 index 70d28180..00000000 --- a/doc/2/core-classes/kuzzle/collection/index.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -code: true -type: page -title: collection -description: Kuzzle:collection ---- - -# collection - -Instantiates a new [Collection](/sdk/java/2/core-classes/collection) object. - ---- - -## collection(collection, [index]) - -| Arguments | Type | Description | -| ------------ | ------ | ------------------------------------------------------ | -| `collection` | string | The name of the collection you want to manipulate | -| `index` | string | The name of the index containing the collection | - -If no `index` is provided, the factory will take the default index set in the main Kuzzle SDK instance. If no default index has been set, an error is thrown. - -The `index` argument takes precedence over the default index. - ---- - -## Return Value - -Returns a [Collection](/sdk/java/2/core-classes/collection) object. - -## Usage - -<<< ./snippets/collection-1.java diff --git a/doc/2/core-classes/kuzzle/collection/snippets/collection-1.java b/doc/2/core-classes/kuzzle/collection/snippets/collection-1.java deleted file mode 100644 index a6ce6494..00000000 --- a/doc/2/core-classes/kuzzle/collection/snippets/collection-1.java +++ /dev/null @@ -1,6 +0,0 @@ - -Collection collection = kuzzle.collection("collection", "index"); - -// or using a default index: -kuzzle.setDefaultIndex("index"); -Collection collection = kuzzle.collection("collection"); diff --git a/doc/2/core-classes/kuzzle/connect/index.md b/doc/2/core-classes/kuzzle/connect/index.md deleted file mode 100644 index b161ca4e..00000000 --- a/doc/2/core-classes/kuzzle/connect/index.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -code: true -type: page -title: connect -description: Kuzzle:connect ---- - -# connect - -Connects to Kuzzle using the `host` parameter provided in the constructor. -Has no effect if `connect` is set to `auto`, unless `disconnect` has been called first. - ---- - -## Return value - -Returns the `Kuzzle` object to allow chaining. - ---- - -## Callback Response - -If a callback has been provided to the `Kuzzle` constructor, it will be called with the `Kuzzle` instance once connected to Kuzzle - -## Usage - -<<< ./snippets/connect-1.java diff --git a/doc/2/core-classes/kuzzle/connect/snippets/connect-1.java b/doc/2/core-classes/kuzzle/connect/snippets/connect-1.java deleted file mode 100644 index d2b41898..00000000 --- a/doc/2/core-classes/kuzzle/connect/snippets/connect-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.connect(); diff --git a/doc/2/core-classes/kuzzle/constructor/index.md b/doc/2/core-classes/kuzzle/constructor/index.md deleted file mode 100644 index 43984d87..00000000 --- a/doc/2/core-classes/kuzzle/constructor/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -code: true -type: page -title: Kuzzle -description: Entry point and main class for the entire SDK -order: 100 ---- - -# Constructor - -This is the main entry point to communicate with Kuzzle. Every other object inherits properties from the `Kuzzle` object. - ---- - -## Kuzzle(host, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------------------- | -| `host` | string | The server name (or the IP address) of a Kuzzle server installation | -| `options` | JSON object | Optional Kuzzle connection configuration | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ------------------- | ----------- | ------------------------------------------------------------------ | -------- | -| `autoQueue` | boolean | Automatically queue all requests during offline mode | `false` | -| `autoReconnect` | boolean | Automatically reconnect after a connection loss | `true` | -| `autoReplay` | boolean | Automatically replay queued requests on a `reconnected` event | `false` | -| `autoResubscribe` | boolean | Automatically renew all subscriptions on a `reconnected` event | `true` | -| `connect` | string | Manually or automatically connect to the Kuzzle instance | `auto` | -| `defaultIndex` | string | Set the default index to use | | -| `headers` | JSON object | Common headers for all sent documents | | -| `volatile` | JSON object | Common volatile data, will be sent to all future requests | | -| `offlineMode` | string | Offline mode configuration | `manual` | -| `port` | integer | Kuzzle network port | 7512 | -| `queueTTL` | integer | Time a queued request is kept during offline mode, in milliseconds | `120000` | -| `queueMaxSize` | integer | Number of maximum requests kept during offline mode | `500` | -| `replayInterval` | integer | Delay between each replayed requests, in milliseconds | `10` | -| `reconnectionDelay` | integer | number of milliseconds between reconnection attempts | `1000` | -| `ssl` | boolean | Switch Kuzzle connection to SSL mode | `false` | - -**Notes:** - -- the `offlineMode` option only accepts the `manual` and `auto` values - ---- - -## Properties - -| Property name | Type | Description | Writable? | -| -------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------- | :-------: | -| `autoQueue` | boolean | Automatically queue all requests during offline mode | Yes | -| `autoReconnect` | boolean | Automatically reconnect after a connection loss | No | -| `autoReplay` | boolean | Automatically replay queued requests on a `reconnected` event | Yes | -| `autoResubscribe` | boolean | Automatically renew all subscriptions on a `reconnected` event | No | -| `defaultIndex` | string | Kuzzle's default index to use | Yes | -| `headers` | JSON object | Common headers for all sent documents. | Yes | -| `host` | string | Target Kuzzle host name/address | No | -| `jwtToken` | string | Token used in requests for authentication. | Yes | -| `offlineQueue` | JSON object | Contains the queued requests during offline mode | No | -| `offlineQueueLoader` | function | Called before dequeuing requests after exiting offline mode, to add items at the beginning of the offline queue | Yes | -| `port` | integer | Kuzzle network port | No | -| `queueFilter` | function | Called during offline mode. Takes a request object as arguments and returns a boolean, indicating if a request can be queued | Yes | -| `queueMaxSize` | integer | Number of maximum requests kept during offline mode | Yes | -| `queueTTL` | integer | Time a queued request is kept during offline mode, in milliseconds | Yes | -| `replayInterval` | integer | Delay between each replayed requests | Yes | -| `reconnectionDelay` | integer | Number of milliseconds between reconnection attempts | No | -| `ssl` | boolean | Connect to Kuzzle using SSL | No | -| `volatile` | JSON object | Common volatile data, will be sent to all future requests | Yes | - -**Notes:** - -- if `connect` is set to `manual`, the `connect` method will have to be called manually -- the kuzzle instance will automatically queue all requests, and play them automatically once a first connection is established, regardless of the `connect` or offline mode option values. -- multiple methods allow passing specific `volatile` data. These `volatile` data will be merged with the global Kuzzle `volatile` object when sending the request, with the request specific `volatile` taking priority over the global ones. -- the `queueFilter` property is a function taking a JSON object as an argument. This object is the request sent to Kuzzle, following the [Kuzzle API](/core/1/api/essentials/query-syntax) format -- if `queueTTL` is set to `0`, requests are kept indefinitely -- The offline buffer acts like a first-in first-out (FIFO) queue, meaning that if the `queueMaxSize` limit is reached, older requests are discarded to make room for new requests -- if `queueMaxSize` is set to `0`, an unlimited number of requests is kept until the buffer is flushed -- the `offlineQueueLoader` must be set with a function, taking no argument, and returning an array of objects containing a `query` member with a Kuzzle query to be replayed, and an optional `cb` member with the corresponding callback to invoke with the query result -- updates to `host`, `port`, `autoReconnect`, `reconnectionDelay` and `sslConnection` properties will only take effect on next `connect` call - ---- - -## Callback response - -If the connection succeeds, resolves to the `Kuzzle` object itself. -If the `connect` option is set to `manual`, the callback will be called after the `connect` method is resolved. - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/kuzzle/constructor/snippets/constructor-1.java b/doc/2/core-classes/kuzzle/constructor/snippets/constructor-1.java deleted file mode 100644 index 4fe6ff7e..00000000 --- a/doc/2/core-classes/kuzzle/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,22 +0,0 @@ - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; - -Options options = new Options(); - -options.setDefaultIndex("some index") - .setAutoReconnect(true), - .setHeaders(new JSONObject().put("someheader", "value")) - .setPort(7512); - -Kuzzle kuzzle = new Kuzzle("localhost", options, new ResponseListener() { - @Override - public void onSuccess(Void object) { - // invoked once connected, object contains the kuzzle instance - } - - @Override - public void onError(JSONObject error) { - // Handle connection error - } -}); diff --git a/doc/2/core-classes/kuzzle/create-index/index.md b/doc/2/core-classes/kuzzle/create-index/index.md deleted file mode 100644 index af0648b2..00000000 --- a/doc/2/core-classes/kuzzle/create-index/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: createIndex -description: Kuzzle:createIndex ---- - -# createIndex - -Create a new empty index, with no associated mapping. - ---- - -## createIndex([index], [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------------------------------------------------------------------------------------- | -| `index` | string | Optional index to query. If no set, defaults to [Kuzzle.defaultIndex](/sdk/java/2/core-classes/kuzzle#properties) | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object with the index creation status. - -## Usage - -<<< ./snippets/create-index-1.java - -> Callback response: - -```json -{ - "acknowledged": true, - "shards_acknowledged": true -} -``` diff --git a/doc/2/core-classes/kuzzle/create-index/snippets/create-index-1.java b/doc/2/core-classes/kuzzle/create-index/snippets/create-index-1.java deleted file mode 100644 index 13dc0831..00000000 --- a/doc/2/core-classes/kuzzle/create-index/snippets/create-index-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.createIndex("myIndex", new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - // result var contains the creation status of myIndex. - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/kuzzle/create-my-credentials/index.md b/doc/2/core-classes/kuzzle/create-my-credentials/index.md deleted file mode 100644 index 57776eed..00000000 --- a/doc/2/core-classes/kuzzle/create-my-credentials/index.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -code: true -type: page -title: createMyCredentials -description: Kuzzle:createMyCredentials ---- - -# createMyCredentials - -Create the current user's credentials for the specified strategy. The credentials required will depend on the authentication plugin and strategy. - ---- - -## createMyCredentials(strategy, credentials, [options], [callback]) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------- | -| `strategy` | string | Strategy you want to create credentials for | -| `credentials` | JSON object | The credentials | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object with the created credentials. - -## Usage - -<<< ./snippets/create-my-credentials-1.java diff --git a/doc/2/core-classes/kuzzle/create-my-credentials/snippets/create-my-credentials-1.java b/doc/2/core-classes/kuzzle/create-my-credentials/snippets/create-my-credentials-1.java deleted file mode 100644 index 85ea1917..00000000 --- a/doc/2/core-classes/kuzzle/create-my-credentials/snippets/create-my-credentials-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -JSONObject credentials = new JSONObject().put("username", "bar"); - -kuzzle.createMyCredentials("local", credentials, new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - // result var contains the new credentials and the kuid of the user - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/kuzzle/delete-my-credentials/index.md b/doc/2/core-classes/kuzzle/delete-my-credentials/index.md deleted file mode 100644 index 2d60d5b9..00000000 --- a/doc/2/core-classes/kuzzle/delete-my-credentials/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -code: true -type: page -title: deleteMyCredentials -description: Kuzzle:deleteMyCredentials ---- - -# deleteMyCredentials - -Delete the current user's credentials for the specified `strategy`. - ---- - -## deleteMyCredentials(strategy, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------- | -| `strategy` | string | Strategy you want to delete credentials from | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object with the query status. - -## Usage - -<<< ./snippets/delete-my-credentials-1.java diff --git a/doc/2/core-classes/kuzzle/delete-my-credentials/snippets/delete-my-credentials-1.java b/doc/2/core-classes/kuzzle/delete-my-credentials/snippets/delete-my-credentials-1.java deleted file mode 100644 index 23ae2c7e..00000000 --- a/doc/2/core-classes/kuzzle/delete-my-credentials/snippets/delete-my-credentials-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.deleteMyCredentials("local", new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - // result var contains the query status - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/kuzzle/disconnect/index.md b/doc/2/core-classes/kuzzle/disconnect/index.md deleted file mode 100644 index d4efaa32..00000000 --- a/doc/2/core-classes/kuzzle/disconnect/index.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -code: true -type: page -title: disconnect -description: Kuzzle:disconnect ---- - -# disconnect - -Closes the current connection, and frees all allocated resources. -Contrary to the `offline` state (when the network connection is unexpectedly lost), `disconnect()` invalidates the instance, which cannot be used until [connect()](/sdk/java/2/core-classes/kuzzle/connect) is explicitly called. -This action does not trigger a `disconnected` event since this event is triggered when an unexpected disconnection occur. - -## Usage - -<<< ./snippets/disconnect-1.java diff --git a/doc/2/core-classes/kuzzle/disconnect/snippets/disconnect-1.java b/doc/2/core-classes/kuzzle/disconnect/snippets/disconnect-1.java deleted file mode 100644 index 80a048ab..00000000 --- a/doc/2/core-classes/kuzzle/disconnect/snippets/disconnect-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.disconnect(); diff --git a/doc/2/core-classes/kuzzle/flush-queue/index.md b/doc/2/core-classes/kuzzle/flush-queue/index.md deleted file mode 100644 index c272949e..00000000 --- a/doc/2/core-classes/kuzzle/flush-queue/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -code: true -type: page -title: flushQueue -description: Kuzzle:flushQueue ---- - -# flushQueue - -Empties the offline queue without replaying it. - ---- - -## Return Value - -Returns the `Kuzzle` SDK instance to allow chaining. - -## Usage - -<<< ./snippets/flush-queue-1.java diff --git a/doc/2/core-classes/kuzzle/flush-queue/snippets/flush-queue-1.java b/doc/2/core-classes/kuzzle/flush-queue/snippets/flush-queue-1.java deleted file mode 100644 index 3c277c58..00000000 --- a/doc/2/core-classes/kuzzle/flush-queue/snippets/flush-queue-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.flushQueue(); diff --git a/doc/2/core-classes/kuzzle/get-all-statistics/index.md b/doc/2/core-classes/kuzzle/get-all-statistics/index.md deleted file mode 100644 index 200c22d5..00000000 --- a/doc/2/core-classes/kuzzle/get-all-statistics/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -code: true -type: page -title: getAllStatistics -description: Kuzzle:getAllStatistics ---- - -# getAllStatistics - -> Callback response example: - -```json -[ - { - "connections": { "socketio": 1 }, - "ongoingRequests": { "rest": 0, "socketio": 0 }, - "completedRequests": { "mqtt": 37, "socketio": 17 }, - "failedRequests": { "socketio": 1 }, - "timestamp": "1453110641308" - }, - { - "connections": { "socketio": 1 }, - "ongoingRequests": { "rest": 0, "socketio": 0 }, - "completedRequests": { "socketio": 34 }, - "failedRequests": { "socketio": 3 }, - "timestamp": "1453110642308" - }, - { - "connections": {}, - "ongoingRequests": { "rest": 0, "socketio": 0 }, - "completedRequests": { "socketio": 40 }, - "failedRequests": {}, - "timestamp": "1453110643308" - } -] -``` - -Kuzzle monitors active connections, and ongoing/completed/failed requests. -This method returns all available statistics from Kuzzle. - ---- - -## getAllStatistics([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -### Callback Response - -Returns an array of JSON objects that each contain a statistics frame. - -## Usage - -<<< ./snippets/get-all-statistics-1.java diff --git a/doc/2/core-classes/kuzzle/get-all-statistics/snippets/get-all-statistics-1.java b/doc/2/core-classes/kuzzle/get-all-statistics/snippets/get-all-statistics-1.java deleted file mode 100644 index e54c9609..00000000 --- a/doc/2/core-classes/kuzzle/get-all-statistics/snippets/get-all-statistics-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.getAllStatistics(new ResponseListener() { - @Override - public void onSuccess(JSONObject[] frames) { - // loop through all returned frames - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}; diff --git a/doc/2/core-classes/kuzzle/get-auto-refresh/index.md b/doc/2/core-classes/kuzzle/get-auto-refresh/index.md deleted file mode 100644 index b939352f..00000000 --- a/doc/2/core-classes/kuzzle/get-auto-refresh/index.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -code: true -type: page -title: getAutoRefresh -description: Kuzzle:getAutoRefresh ---- - -# getAutoRefresh - -The `autoRefresh` flag, when set to true, will make Kuzzle perform a -[`refresh`](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/docs-refresh.html) request -immediately after each write request, causing documents to be immediately visible in a search. - -The `getAutoRefresh` function returns the current `autoRefresh` status for the given index. - -:::warning -A refresh operation comes with some performance costs. - -While forcing the autoRefresh can be convenient on a development or test environmnent, we recommend that you avoid -using it in production or at least carefully monitor its implications before using it. -::: - ---- - -#### getAutoRefresh([index], [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------------------------------------------------------------------------------------- | -| `index` | string | Optional index to query. If no set, defaults to [Kuzzle.defaultIndex](/sdk/java/2/core-classes/kuzzle#properties) | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a boolean with the index `autoRefresh` status. - -## Usage - -<<< ./snippets/get-auto-refresh-1.java diff --git a/doc/2/core-classes/kuzzle/get-auto-refresh/snippets/get-auto-refresh-1.java b/doc/2/core-classes/kuzzle/get-auto-refresh/snippets/get-auto-refresh-1.java deleted file mode 100644 index d1264b20..00000000 --- a/doc/2/core-classes/kuzzle/get-auto-refresh/snippets/get-auto-refresh-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.getAutoRefresh("myIndex", new ResponseListener() { - @Override - public void onSuccess(Boolean autoRefresh) { - // autoRefresh var contains the autoRefresh status of myIndex. - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/kuzzle/get-jwt-token/index.md b/doc/2/core-classes/kuzzle/get-jwt-token/index.md deleted file mode 100644 index a2b37ff1..00000000 --- a/doc/2/core-classes/kuzzle/get-jwt-token/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -code: true -type: page -title: getJwtToken -description: Kuzzle:getJwtToken ---- - -# getJwtToken - -Get internal jwtToken used to request kuzzle. - ---- - -## Return Value - -Returns the stored JWT as a string value. - -## Usage - -<<< ./snippets/get-jwt-token-1.java diff --git a/doc/2/core-classes/kuzzle/get-jwt-token/snippets/get-jwt-token-1.java b/doc/2/core-classes/kuzzle/get-jwt-token/snippets/get-jwt-token-1.java deleted file mode 100644 index 748795f1..00000000 --- a/doc/2/core-classes/kuzzle/get-jwt-token/snippets/get-jwt-token-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -String jwtToken = kuzzle.getJwtToken(); diff --git a/doc/2/core-classes/kuzzle/get-my-credentials/index.md b/doc/2/core-classes/kuzzle/get-my-credentials/index.md deleted file mode 100644 index f32296b0..00000000 --- a/doc/2/core-classes/kuzzle/get-my-credentials/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: getMyCredentials -description: Kuzzle:getMyCredentials ---- - -# getMyCredentials - -Get [credential information](/core/1/guides/essentials/user-authentication#user-credentials) for the current user. - ---- - -## getMyCredentials(strategy, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `strategy` | string | Strategy you want to get credentials from | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object with the credentials for the provided authentication strategy. - -## Usage - -<<< ./snippets/get-my-credentials-1.java - -> Callback response - -```json -{ - "username": "foo", - "kuid": "" -} -``` diff --git a/doc/2/core-classes/kuzzle/get-my-credentials/snippets/get-my-credentials-1.java b/doc/2/core-classes/kuzzle/get-my-credentials/snippets/get-my-credentials-1.java deleted file mode 100644 index afe80354..00000000 --- a/doc/2/core-classes/kuzzle/get-my-credentials/snippets/get-my-credentials-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.getMyCredentials("local", new ResponseListener() { - @Override - public void onSuccess(JSONObject credentials) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/kuzzle/get-my-rights/index.md b/doc/2/core-classes/kuzzle/get-my-rights/index.md deleted file mode 100644 index c8fd5a9d..00000000 --- a/doc/2/core-classes/kuzzle/get-my-rights/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -code: true -type: page -title: getMyRights -description: Kuzzle:getMyRights ---- - -# getMyRights - -Gets the rights for the current user. - ---- - -## getMyRights([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of rights. - -## Usage - -<<< ./snippets/get-my-rights-1.java - -> Callback response - -```json -[ - { - "controller": "my-controller", - "action": "my-action", - "index": "*", - "collection": "*", - "value": "allowed" - }, - { - "controller": "another-controller", - "action": "*", - "index": "my-index", - "collection": "*", - "value": "conditional" - } -] -``` diff --git a/doc/2/core-classes/kuzzle/get-my-rights/snippets/get-my-rights-1.java b/doc/2/core-classes/kuzzle/get-my-rights/snippets/get-my-rights-1.java deleted file mode 100644 index e6e02008..00000000 --- a/doc/2/core-classes/kuzzle/get-my-rights/snippets/get-my-rights-1.java +++ /dev/null @@ -1,13 +0,0 @@ - - -kuzzle - .security - .getMyRights(new ResponseListener() { - @Override - public void onSuccess(JSONObject[] rights) { - } - - @Override - public void onError(JSONObject error) { - } - }); diff --git a/doc/2/core-classes/kuzzle/get-server-info/index.md b/doc/2/core-classes/kuzzle/get-server-info/index.md deleted file mode 100644 index e86a5787..00000000 --- a/doc/2/core-classes/kuzzle/get-server-info/index.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -code: true -type: page -title: getServerInfo -description: Kuzzle:getServerInfo ---- - -# getServerInfo - -> Callback response example: - -```json -{ - "kuzzle": { - "api": { - "routes": { - "controller1": { - "action1": { - "controller": "controller1", - "action": "action1", - "http": { - "verb": "GET", - "url": "/action1/url" - } - }, - "action2": { - "controller": "controller1", - "action": "action2", - "http": { - "verb": "POST", - "url": "/action2/url" - } - }, - { - "...": "..." - } - }, - "pluginName/controller": { - "action": { - "controller": "pluginName/controller", - "action": "action", - "http": { - "verb": "GET", - "url": "/action/url" - } - }, - { - "...": " ..." - } - }, - { - "...": "..." - } - }, - "version": "" - }, - "memoryUsed": 12345, - "nodeVersion": "v6.9.5", - "plugins": {}, - "system": { - "cpus": [ - { - "cpu1": "informations" - }, - { - "...": "..." - } - ], - "memory": { - "free": 123456, - "total": 1234567 - } - }, - "uptime": "", - "version": "" - }, - "services": { - "internalCache": { - "kuzzle memory cache": "informations", - "...": "..." - }, - "memoryStorage": { - "API memory storage": "informations", - "...": "..." - }, - { - "...": "..." - } - } -} -``` - -Retrieves information about Kuzzle plugins and active services. - ---- - -## getServerInfo([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a JSON object containing server information. - -## Usage - -<<< ./snippets/get-server-info-1.java diff --git a/doc/2/core-classes/kuzzle/get-server-info/snippets/get-server-info-1.java b/doc/2/core-classes/kuzzle/get-server-info/snippets/get-server-info-1.java deleted file mode 100644 index f9a0f8ac..00000000 --- a/doc/2/core-classes/kuzzle/get-server-info/snippets/get-server-info-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.getServerInfo(new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - // Handle success - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/kuzzle/get-statistics/index.md b/doc/2/core-classes/kuzzle/get-statistics/index.md deleted file mode 100644 index 1c365fa3..00000000 --- a/doc/2/core-classes/kuzzle/get-statistics/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -code: true -type: page -title: getStatistics -description: Kuzzle:getStatistics ---- - -# getStatistics - -> Without argument, retrieves the last statistic frame in an array: -> When providing a timestamp, retrieves all frames recorded after that timestamp: -> Kuzzle server monitors active connections, and ongoing/completed/failed requests. -> This method returns either the last statistics frame, or a set of frames starting from a provided timestamp. - ---- - -## getStatistics([timestamp], [options], callback) - -| Arguments | Type | Description | -| ----------- | ----------- | ---------------------------------------------------------------- | -| `timestamp` | Epoch time | Optional starting time from which the frames are to be retrieved | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - -**Note:** Kuzzle statistics are cleaned up regularly. If the timestamp is set too far in the past, then this method will return all available statistics. - ---- - -### Callback Response - -Returns an `array` containing one or more statistics frame (as JSON objects). - -## Usage - -<<< ./snippets/get-statistics-1.java - -<<< ./snippets/get-statistics-2.java - -> Callback response: - -```json -[ - { - "connections": { "socketio": 1 }, - "ongoingRequests": { "rest": 0, "socketio": 0 }, - "completedRequests": { "mqtt": 37, "socketio": 17 }, - "failedRequests": { "socketio": 1 }, - "timestamp": "1453110641308" - } -] -``` diff --git a/doc/2/core-classes/kuzzle/get-statistics/snippets/get-statistics-1.java b/doc/2/core-classes/kuzzle/get-statistics/snippets/get-statistics-1.java deleted file mode 100644 index 269a5471..00000000 --- a/doc/2/core-classes/kuzzle/get-statistics/snippets/get-statistics-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.getStatistics(new ResponseListener() { - @Override - public void onSuccess(JSONObject[] statistics) { - // ... - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/kuzzle/get-statistics/snippets/get-statistics-2.java b/doc/2/core-classes/kuzzle/get-statistics/snippets/get-statistics-2.java deleted file mode 100644 index 0e852ace..00000000 --- a/doc/2/core-classes/kuzzle/get-statistics/snippets/get-statistics-2.java +++ /dev/null @@ -1,13 +0,0 @@ - -// Date can be either in ISO format or a timestamp (utc, in milliseconds) -kuzzle.getStatistics("2015-11-15T13:36:45.558Z", new ResponseListener() { - @Override - public void onSuccess(JSONObject[] statistics) { - // ... - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}; diff --git a/doc/2/core-classes/kuzzle/index.md b/doc/2/core-classes/kuzzle/index.md deleted file mode 100644 index 54c7fde2..00000000 --- a/doc/2/core-classes/kuzzle/index.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -code: true -type: branch -title: Kuzzle -description: Kuzzle documentation -order: 400 ---- diff --git a/doc/2/core-classes/kuzzle/list-collections/index.md b/doc/2/core-classes/kuzzle/list-collections/index.md deleted file mode 100644 index 0b01279b..00000000 --- a/doc/2/core-classes/kuzzle/list-collections/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -code: true -type: page -title: listCollections -description: Kuzzle:listCollections ---- - -# listCollections - -Returns the list of known collections contained in a specified index. - ---- - -## listCollections([index], [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------------- | -| `index` | string | Index containing the collections to be listed | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `from` | integer | Determines the starting point of the pagination. By default, start at the beggining | `0` | -| `size` | integer | Determines the size of the returned result set. By default, no limit is applied | `undefined` | -| `type` | string | Get either `stored` collections or `realtime` ones. By default, list `all` collections | `all` | - -If no `index` argument is provided, the `defaultIndex` property is used. If no default index is found, this method throws an error. - ---- - -## Callback Response - -Returns an array of JSON objects containing the list of stored and/or realtime collections on the provided index. - -## Usage - -<<< ./snippets/list-collections-1.java - -> Callback response: - -```json -[ - { "name": "realtime_1", "type": "realtime" }, - { "name": "realtime_2", "type": "realtime" }, - { "name": "realtime_...", "type": "realtime" }, - { "name": "realtime_n", "type": "realtime" }, - { "name": "stored_1", "type": "stored" }, - { "name": "stored_2", "type": "stored" }, - { "name": "stored_...", "type": "stored" }, - { "name": "stored_n", "type": "stored" } -] -``` diff --git a/doc/2/core-classes/kuzzle/list-collections/snippets/list-collections-1.java b/doc/2/core-classes/kuzzle/list-collections/snippets/list-collections-1.java deleted file mode 100644 index 5f40b4bc..00000000 --- a/doc/2/core-classes/kuzzle/list-collections/snippets/list-collections-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.listCollections("index", new ResponseListener() { - @Override - public void onSuccess(JSONObject[] collections) { - // ... - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/kuzzle/list-indexes/index.md b/doc/2/core-classes/kuzzle/list-indexes/index.md deleted file mode 100644 index e117e35c..00000000 --- a/doc/2/core-classes/kuzzle/list-indexes/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -code: true -type: page -title: listIndexes -description: Kuzzle:listIndexes ---- - -# listIndexes - -Returns the list of indexes stored in Kuzzle. - ---- - -## listIndexes([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an `array` of index names. - -## Usage - -<<< ./snippets/list-indexes-1.java - -> Callback response: - -```json -["index", "another index", "..."] -``` diff --git a/doc/2/core-classes/kuzzle/list-indexes/snippets/list-indexes-1.java b/doc/2/core-classes/kuzzle/list-indexes/snippets/list-indexes-1.java deleted file mode 100644 index 9fa6a116..00000000 --- a/doc/2/core-classes/kuzzle/list-indexes/snippets/list-indexes-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.listIndexes(new ResponseListener() { - @Override - public void onSuccess(String[] result) { - // ... - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/kuzzle/login/index.md b/doc/2/core-classes/kuzzle/login/index.md deleted file mode 100644 index 4180a4b7..00000000 --- a/doc/2/core-classes/kuzzle/login/index.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -code: true -type: page -title: login -description: Kuzzle:login ---- - -# login - -Login a user using a specified strategy and their credentials. - -If the Kuzzle response contains a JWT Token, the Kuzzle SDK token is set and the `loginAttempt` event is fired immediately with the following object: -`{ success: true }` -This is the case, for instance, with the `local` authentication strategy. - -If the request succeeds but there is no token, then it means that the chosen strategy is a two-steps authentication method, such as the OAUTH strategy. In that case, the `loginAttempt` event is **not** fired. To complete the login, the `setJwtToken` method must be called either with a token or with an appropriate Kuzzle response. - -If the login attempt fails, the `loginAttempt` event is fired with the following response: -`{ success: false, error: 'error message' }` - -:::info -This method is non-queuable, meaning that during offline mode, it will be discarded and the callback will be called with an error. -::: - ---- - -## login(strategy, [credentials], [expiresIn], [callback]) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------------------ | -| `strategy` | string | Authentication strategy (local, facebook, github, ...) | -| `credentials` | JSON object | Optional login credentials, depending on the strategy | -| `expiresIn` | _varies_ | Login expiration time | -| `callback` | function | Optional callback handling the response | - -**Note:** If the `expiresIn` argument is not set, the default token expiration value will be taken from the Kuzzle server configuration. - -By default, Kuzzle comes with the [kuzzle-plugin-auth-passport-local](https://github.com/kuzzleio/kuzzle-plugin-auth-passport-local) plugin, which provides the `local` authentication strategy. -This strategy requires a `username` and `password` as `credentials` - ---- - -## Callback Response - -Returns a JSON object containing the Kuzzle response. - -## Usage - -<<< ./snippets/login-1.java diff --git a/doc/2/core-classes/kuzzle/login/snippets/login-1.java b/doc/2/core-classes/kuzzle/login/snippets/login-1.java deleted file mode 100644 index db475b1a..00000000 --- a/doc/2/core-classes/kuzzle/login/snippets/login-1.java +++ /dev/null @@ -1,16 +0,0 @@ - -JSONObject credentials = new JSONObject() - .put("username", "John Doe") - .put("password", "my secret password"); - -kuzzle.login("local", credentials, 30000, new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - // ... - } - - @Override - public void onError() { - // Handle error - } -}); diff --git a/doc/2/core-classes/kuzzle/logout/index.md b/doc/2/core-classes/kuzzle/logout/index.md deleted file mode 100644 index 6bf51b09..00000000 --- a/doc/2/core-classes/kuzzle/logout/index.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -code: true -type: page -title: logout -description: Kuzzle:logout ---- - -# logout - -Logs the user out. - -:::info -This method is non-queuable, meaning that during offline mode, it will be discarded and the callback will be called with an error. -::: - ---- - -## logout([callback]) - -| Arguments | Type | Description | -| ---------- | -------- | --------------------------------------- | -| `callback` | function | Optional callback handling the response | - -This method empties the `jwtToken` property - ---- - -## Return value - -Returns the `Kuzzle` SDK object to allow chaining. - ---- - -## Callback Response - -Returns the `Kuzzle` SDK object once the logout process is complete, either successfully or not. -The `Kuzzle` SDK object will unset the `jwtToken` property if the user is successfully logged out. - -## Usage - -<<< ./snippets/logout-1.java diff --git a/doc/2/core-classes/kuzzle/logout/snippets/logout-1.java b/doc/2/core-classes/kuzzle/logout/snippets/logout-1.java deleted file mode 100644 index df71fa54..00000000 --- a/doc/2/core-classes/kuzzle/logout/snippets/logout-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.logout(new ResponseListener() { - @Override - public void onSuccess(Void result) { - // ... - } - - @Override - public void onError() { - // Handle error - } -}); diff --git a/doc/2/core-classes/kuzzle/memory-storage/index.md b/doc/2/core-classes/kuzzle/memory-storage/index.md deleted file mode 100644 index 8f040194..00000000 --- a/doc/2/core-classes/kuzzle/memory-storage/index.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -code: true -type: page -title: memoryStorage -description: Kuzzle:memoryStorage ---- - -## memoryStorage - -A [MemoryStorage](/sdk/java/2/core-classes/memory-storage) singleton. diff --git a/doc/2/core-classes/kuzzle/now/index.md b/doc/2/core-classes/kuzzle/now/index.md deleted file mode 100644 index 670e315e..00000000 --- a/doc/2/core-classes/kuzzle/now/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -code: true -type: page -title: now -description: Kuzzle:now ---- - -# now - -Retrieves the current Kuzzle time. - ---- - -## now([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an `integer` containing the current Kuzzle time, encoded as an UTC Epoch time in milliseconds. - -## Usage - -<<< ./snippets/now-1.java - -> Callback response: - -```json -1447151167622 -``` diff --git a/doc/2/core-classes/kuzzle/now/snippets/now-1.java b/doc/2/core-classes/kuzzle/now/snippets/now-1.java deleted file mode 100644 index 2e94afb5..00000000 --- a/doc/2/core-classes/kuzzle/now/snippets/now-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.now(new ResponseListener() { - @Override - public void onSuccess(Date object) { - // 'object' contains the Kuzzle timestamp (utc, in milliseconds) - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/kuzzle/query/index.md b/doc/2/core-classes/kuzzle/query/index.md deleted file mode 100644 index 6debb90e..00000000 --- a/doc/2/core-classes/kuzzle/query/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -code: true -type: page -title: query -description: Kuzzle:query ---- - -## query - -Base method used to send queries to Kuzzle, following the [API Documentation](/core/1/api). - -:::warning -This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods. -Refer to Kuzzle's API Reference [here](/core/1/api) -::: - ---- - -## query(queryArgs, query, [options], [callback]) - -| Argument | Type | Description | -| ----------- | ----------- | -------------------- | -| `queryArgs` | JSON object | Query base arguments | -| `query` | JSON object | Query to execute | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback | - ---- - -## queryArgs - -`queryArgs` is a JSON object allowing Kuzzle to route your query to the right API method: - -| Option | Type | Description | Required? | -| ------------ | ------ | --------------------------------------- | --------- | -| `controller` | string | API Controller argument | required | -| `action` | string | API Controller action | required | -| `index` | string | Index concerned by the action | optional | -| `collection` | string | Data collection concerned by the action | optional | - ---- - -## query - -## `query` is a JSON object containing arguments specific to the query, such as a `body` property, a JWT hash, a document `_id`, or generic query options (such as `from` or `size` for [search queries](/core/1/api/controllers/document/search)) - -## Options - -| Option | Type | Description | Default | -| ---------- | ----------- | ------------------------------------------------------------- | ------- | -| `volatile` | JSON object | Additional information passed to notifications to other users | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. - ---- - -## Callback Response - -Returns a `JSON object` containing the raw Kuzzle response. - -## Usage - -<<< ./snippets/query-1.java - -> Callback response: - -```json -{ - "error": null, - "result": { - "action": "action", - "controller": "controller", - "requestId": "bf87b930-7c02-11e5-ab10-dfa9e9fd2e07", - "other properties": "depends of the query made" - } -} -``` diff --git a/doc/2/core-classes/kuzzle/query/snippets/query-1.java b/doc/2/core-classes/kuzzle/query/snippets/query-1.java deleted file mode 100644 index 6e407d5e..00000000 --- a/doc/2/core-classes/kuzzle/query/snippets/query-1.java +++ /dev/null @@ -1,22 +0,0 @@ - -QueryArgs args = new QueryArgs(); -args.controller = "controller"; -args.action = "action"; - -JSONObject query = new JSONObject() - .put("body", new JSONObject() - .put("foo", "bar") - ) - .put("other", "argument"); - -kuzzle.query(args, query, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/kuzzle/refresh-index/index.md b/doc/2/core-classes/kuzzle/refresh-index/index.md deleted file mode 100644 index a92465f7..00000000 --- a/doc/2/core-classes/kuzzle/refresh-index/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -code: true -type: page -title: refreshIndex -description: Kuzzle:refreshIndex ---- - -# refreshIndex - -When writing or deleting documents in Kuzzle, the update needs to be indexed before being reflected -in the search index. -By default, this operation can take up to 1 second. - -Given an index, the `refresh` action forces a [`refresh`](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/docs-refresh.html), -on it, making the documents visible to search immediately. - -:::warning -A refresh operation comes with some performance costs. - -From the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/5.6/docs-refresh.html): - -> "While a refresh is much lighter than a commit, it still has a performance cost. A manual refresh can be useful when writing tests, but don’t do a manual refresh every time you index a document in production; it will hurt your performance. Instead, your application needs to be aware of the near real-time nature of Elasticsearch and make allowances for it." -::: - ---- - -## refreshIndex([index], [options], [callback]) - -| Argument | Type | Description | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- | -| `index` | string | _Optional_. The index to refresh. If not set, defaults to [kuzzle.defaultIndex](/sdk/java/2/core-classes/kuzzle#properties). | -| `options` | JSON object | Optional parameters | -| `callback` | function | _Optional_. Callback handling the response. | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. - ---- - -## Callback Response - -Returns a JSON structure matching the response from Elasticsearch. - -## Usage - -<<< ./snippets/refresh-index-1.java diff --git a/doc/2/core-classes/kuzzle/refresh-index/snippets/refresh-index-1.java b/doc/2/core-classes/kuzzle/refresh-index/snippets/refresh-index-1.java deleted file mode 100644 index a3f53613..00000000 --- a/doc/2/core-classes/kuzzle/refresh-index/snippets/refresh-index-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.refreshIndex("myIndex"); diff --git a/doc/2/core-classes/kuzzle/remove-all-listeners/index.md b/doc/2/core-classes/kuzzle/remove-all-listeners/index.md deleted file mode 100644 index ac32ec98..00000000 --- a/doc/2/core-classes/kuzzle/remove-all-listeners/index.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -code: true -type: page -title: removeAllListeners -description: Kuzzle:removeAllListeners ---- - -# removeAllListeners - -Removes all listeners, either from a specific event or from all events - ---- - -## removeAllListeners([event]) - -| Arguments | Type | Description | -| --------- | ------ | -------------------------------------------------------------------------------- | -| `event` | string | One of the event described in the `Event Handling` section of this documentation | - ---- - -## Return Value - -Returns the `Kuzzle` object to allow chaining. - -## Usage - -<<< ./snippets/remove-all-listeners-1.java diff --git a/doc/2/core-classes/kuzzle/remove-all-listeners/snippets/remove-all-listeners-1.java b/doc/2/core-classes/kuzzle/remove-all-listeners/snippets/remove-all-listeners-1.java deleted file mode 100644 index 1f1c54c2..00000000 --- a/doc/2/core-classes/kuzzle/remove-all-listeners/snippets/remove-all-listeners-1.java +++ /dev/null @@ -1,6 +0,0 @@ - -// Removes all listeners on the "unsubscribed" global event -kuzzle.removeAllListeners(Event.disconnected); - -// Removes all listeners on all global events -kuzzle.removeAllListeners(); diff --git a/doc/2/core-classes/kuzzle/remove-listener/index.md b/doc/2/core-classes/kuzzle/remove-listener/index.md deleted file mode 100644 index 55b43059..00000000 --- a/doc/2/core-classes/kuzzle/remove-listener/index.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -code: true -type: page -title: removeListener -description: Kuzzle:removeListener ---- - -# removeListener - -Remove a listener from an event. - ---- - -## removeListener(event, callback) - -| Arguments | Type | Description | -| ---------- | --------------- | --------------------------------------------------------------------------------- | -| `event` | string | One of the events described in the `Event Handling` section of this documentation | -| `callback` | function/object | the callback | - ---- - -## Return Value - -Returns the `Kuzzle` object to allow chaining. - -## Usage - -<<< ./snippets/remove-listener-1.java diff --git a/doc/2/core-classes/kuzzle/remove-listener/snippets/remove-listener-1.java b/doc/2/core-classes/kuzzle/remove-listener/snippets/remove-listener-1.java deleted file mode 100644 index cd1aa99d..00000000 --- a/doc/2/core-classes/kuzzle/remove-listener/snippets/remove-listener-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.removeListener(Event.disconnected, eventListener); diff --git a/doc/2/core-classes/kuzzle/replay-queue/index.md b/doc/2/core-classes/kuzzle/replay-queue/index.md deleted file mode 100644 index 40fd9632..00000000 --- a/doc/2/core-classes/kuzzle/replay-queue/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -code: true -type: page -title: replayQueue -description: Kuzzle:replayQueue ---- - -# replayQueue - -Replays the requests queued during offline mode. Works only if the SDK is not in a `disconnected` state, and if the `autoReplay` option is set to `false`. - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. - -## Usage - -<<< ./snippets/replay-queue-1.java diff --git a/doc/2/core-classes/kuzzle/replay-queue/snippets/replay-queue-1.java b/doc/2/core-classes/kuzzle/replay-queue/snippets/replay-queue-1.java deleted file mode 100644 index 5f4f4ed7..00000000 --- a/doc/2/core-classes/kuzzle/replay-queue/snippets/replay-queue-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.replayQueue(); diff --git a/doc/2/core-classes/kuzzle/security/index.md b/doc/2/core-classes/kuzzle/security/index.md deleted file mode 100644 index cb913ffa..00000000 --- a/doc/2/core-classes/kuzzle/security/index.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -code: true -type: page -title: security -description: Kuzzle:security ---- - -# security - -A [Security](/sdk/java/2/core-classes/security) singleton. diff --git a/doc/2/core-classes/kuzzle/set-auto-refresh/index.md b/doc/2/core-classes/kuzzle/set-auto-refresh/index.md deleted file mode 100644 index 722e87f1..00000000 --- a/doc/2/core-classes/kuzzle/set-auto-refresh/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -code: true -type: page -title: setAutoRefresh -description: Kuzzle:setAutoRefresh ---- - -# setAutoRefresh - -The `autoRefresh` flag, when set to true, will make Kuzzle perform a -[`refresh`](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/docs-refresh.html) request -immediately after each write request, causing documents to be immediately visible in a search. - -Given an index, the `setAutoRefresh` function updates its `autoRefresh` status. - -:::warning -A refresh operation comes with some performance costs. - - -While forcing the autoRefresh can be convenient on a development or test environmnent, we recommend that you avoid -using it in production or at least carefully monitor its implications before using it. -::: - ---- - -## setAutoRefresh([index], autoRefresh, [options], [callback]) - -| Argument | Type | Description | -| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -| `index` | string | _Optional_ The index to set the `autoRefresh` for. If not set, defaults to [kuzzle.defaultIndex](/sdk/java/2/core-classes/kuzzle#properties). | -| `autoRefresh` | boolean | The value to set for the `autoRefresh` setting. | -| `options` | JSON object | Optional parameters | -| `callback` | function | _Optional_ Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. - ---- - -## Callback Response - -Returns a boolean with the new `autoRefresh` status. - -## Usage - -<<< ./snippets/set-auto-refresh-1.java diff --git a/doc/2/core-classes/kuzzle/set-auto-refresh/snippets/set-auto-refresh-1.java b/doc/2/core-classes/kuzzle/set-auto-refresh/snippets/set-auto-refresh-1.java deleted file mode 100644 index 1adaa881..00000000 --- a/doc/2/core-classes/kuzzle/set-auto-refresh/snippets/set-auto-refresh-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.setAutoRefresh("myIndex", true); diff --git a/doc/2/core-classes/kuzzle/set-default-index/index.md b/doc/2/core-classes/kuzzle/set-default-index/index.md deleted file mode 100644 index c69c219c..00000000 --- a/doc/2/core-classes/kuzzle/set-default-index/index.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -code: true -type: page -title: setDefaultIndex -description: Kuzzle:setDefaultIndex ---- - -# setDefaultIndex - -Set the default index. Has the same effect than the `defaultIndex` constructor option. - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. diff --git a/doc/2/core-classes/kuzzle/set-headers/index.md b/doc/2/core-classes/kuzzle/set-headers/index.md deleted file mode 100644 index baff9fb6..00000000 --- a/doc/2/core-classes/kuzzle/set-headers/index.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -code: true -type: page -title: setHeaders -description: Kuzzle:setHeaders ---- - -# setHeaders - -This is a helper function returning itself, allowing to easily chain calls. - ---- - -## setHeaders(content, [replace]) - -| Arguments | Type | Description | -| --------- | ----------- | ------------------------------------------------------------------------- | -| `content` | JSON Object | New content | -| `replace` | boolean | true: replace the current content with the provided data, false: merge it | - -**Note:** by default, the `replace` argument is set to `false` - ---- - -## Return value - -Returns the `Kuzzle` object to allow chaining. - -## Usage - -<<< ./snippets/set-headers-1.java diff --git a/doc/2/core-classes/kuzzle/set-headers/snippets/set-headers-1.java b/doc/2/core-classes/kuzzle/set-headers/snippets/set-headers-1.java deleted file mode 100644 index 74fe0517..00000000 --- a/doc/2/core-classes/kuzzle/set-headers/snippets/set-headers-1.java +++ /dev/null @@ -1,4 +0,0 @@ - -JSONObject headers = new JSONObject().put("someContent", "someValue"); - -kuzzle.setHeaders(headers, true); diff --git a/doc/2/core-classes/kuzzle/set-jwt-token/index.md b/doc/2/core-classes/kuzzle/set-jwt-token/index.md deleted file mode 100644 index b92610bd..00000000 --- a/doc/2/core-classes/kuzzle/set-jwt-token/index.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -code: true -type: page -title: setJwtToken -description: Kuzzle:setJwtToken ---- - -# setJwtToken - -Sets the internal JWT token which will be used when making requests to Kuzzle. - -If the provided token is valid, a `loginAttempt` event is fired with the following object: -`{ success: true }` - -If not, the `loginAttempt` event is fired with the following response: -`{ success: false, error: 'error message' }` - ---- - -## setJwtToken(jwtToken) - -| Arguments | Type | Description | -| ---------- | ------ | ----------------------------------- | -| `jwtToken` | string | Previously generated JSON Web Token | - ---- - -## setJwtToken(kuzzleResponse) - -| Arguments | Type | Description | -| ---------------- | ----------- | ----------------------------------------------------------- | -| `kuzzleResponse` | JSON object | Final Kuzzle response from a 2-steps authentication process | - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. - -## Usage - -<<< ./snippets/set-jwt-token-1.java diff --git a/doc/2/core-classes/kuzzle/set-jwt-token/snippets/set-jwt-token-1.java b/doc/2/core-classes/kuzzle/set-jwt-token/snippets/set-jwt-token-1.java deleted file mode 100644 index d87640d2..00000000 --- a/doc/2/core-classes/kuzzle/set-jwt-token/snippets/set-jwt-token-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -// Directly with a JWT Token -kuzzle.setJwtToken("some jwt token"); - -/* - Or with a Kuzzle response. - For instance, the final OAUTH2 response is obtained with a redirection from Kuzzle, - and it can be provided to this method directly. - - Here, "authenticationResponse" is an instance of JSONObject - */ -kuzzle.setJwtToken(authenticationResponse) diff --git a/doc/2/core-classes/kuzzle/start-queuing/index.md b/doc/2/core-classes/kuzzle/start-queuing/index.md deleted file mode 100644 index c9a3d5f0..00000000 --- a/doc/2/core-classes/kuzzle/start-queuing/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -code: true -type: page -title: startQueuing -description: Kuzzle:startQueuing ---- - -# startQueuing - -Starts the requests queuing. Works only in offline mode, and if the [autoQueue](/sdk/java/2/core-classes/kuzzle#properties) option is set to `false`. - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. - -## Usage - -<<< ./snippets/start-queuing-1.java diff --git a/doc/2/core-classes/kuzzle/start-queuing/snippets/start-queuing-1.java b/doc/2/core-classes/kuzzle/start-queuing/snippets/start-queuing-1.java deleted file mode 100644 index 938df064..00000000 --- a/doc/2/core-classes/kuzzle/start-queuing/snippets/start-queuing-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.startQueuing(); diff --git a/doc/2/core-classes/kuzzle/stop-queuing/index.md b/doc/2/core-classes/kuzzle/stop-queuing/index.md deleted file mode 100644 index c9099ff0..00000000 --- a/doc/2/core-classes/kuzzle/stop-queuing/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -code: true -type: page -title: stopQueuing -description: Kuzzle:stopQueuing ---- - -# stopQueuing - -Stops the requests queuing. Works only in offline mode, and if the [autoQueue](/sdk/java/2/core-classes/kuzzle#properties) option is set to `false`. - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. - -## Usage - -<<< ./snippets/stop-queuing-1.java diff --git a/doc/2/core-classes/kuzzle/stop-queuing/snippets/stop-queuing-1.java b/doc/2/core-classes/kuzzle/stop-queuing/snippets/stop-queuing-1.java deleted file mode 100644 index f98144ee..00000000 --- a/doc/2/core-classes/kuzzle/stop-queuing/snippets/stop-queuing-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.stopQueuing(); diff --git a/doc/2/core-classes/kuzzle/unset-jwt-token/index.md b/doc/2/core-classes/kuzzle/unset-jwt-token/index.md deleted file mode 100644 index 7c892003..00000000 --- a/doc/2/core-classes/kuzzle/unset-jwt-token/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -code: true -type: page -title: unsetJwtToken -description: Kuzzle:unsetJwtToken ---- - -# unsetJwtToken - -Unsets the internal JSON Web Token used for authentication, and stops all existing subscriptions. - ---- - -## Return Value - -Returns the `Kuzzle` SDK object to allow chaining. - -## Usage - -<<< ./snippets/unset-jwt-token-1.java diff --git a/doc/2/core-classes/kuzzle/unset-jwt-token/snippets/unset-jwt-token-1.java b/doc/2/core-classes/kuzzle/unset-jwt-token/snippets/unset-jwt-token-1.java deleted file mode 100644 index d4ab38c4..00000000 --- a/doc/2/core-classes/kuzzle/unset-jwt-token/snippets/unset-jwt-token-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -kuzzle.unsetJwtToken(); diff --git a/doc/2/core-classes/kuzzle/update-my-credentials/index.md b/doc/2/core-classes/kuzzle/update-my-credentials/index.md deleted file mode 100644 index 9479d6fe..00000000 --- a/doc/2/core-classes/kuzzle/update-my-credentials/index.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -code: true -type: page -title: updateMyCredentials -description: Kuzzle:updateMyCredentials ---- - -# updateMyCredentials - -Update current user credentials for the specified `strategy`. The credentials to send depend on the authentication plugin and the strategy. - ---- - -## updateMyCredentials(strategy, credentials, [options], [callback]) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------ | -| `strategy` | string | Strategy you want to create credentials in | -| `credentials` | JSON object | The credentials | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback response - -Returns an object reflecting the updated credentials. - -## Usage - -<<< ./snippets/update-my-credentials-1.java diff --git a/doc/2/core-classes/kuzzle/update-my-credentials/snippets/update-my-credentials-1.java b/doc/2/core-classes/kuzzle/update-my-credentials/snippets/update-my-credentials-1.java deleted file mode 100644 index 4e55cf5f..00000000 --- a/doc/2/core-classes/kuzzle/update-my-credentials/snippets/update-my-credentials-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -JSONObject credentials = new JSONObject().put("username", "bar"); - -kuzzle.updateMyCredentials("local", credentials, new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - // result var contains the updated credentials and the kuid of the user - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/kuzzle/update-self/index.md b/doc/2/core-classes/kuzzle/update-self/index.md deleted file mode 100644 index 64f078f7..00000000 --- a/doc/2/core-classes/kuzzle/update-self/index.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -code: true -type: page -title: updateSelf -description: Kuzzle:updateSelf ---- - -# updateSelf - ---- - -## updateSelf(content, [options], [callback]) - -Performs a partial update on the current user. - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------- | -| `content` | JSON Object | A plain javascript object representing the user | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `Kuzzle` SDK object to allow chaining. - ---- - -## Callback Response - -Returns the updated user object. - -## Usage - -<<< ./snippets/update-self-1.java diff --git a/doc/2/core-classes/kuzzle/update-self/snippets/update-self-1.java b/doc/2/core-classes/kuzzle/update-self/snippets/update-self-1.java deleted file mode 100644 index d562c35a..00000000 --- a/doc/2/core-classes/kuzzle/update-self/snippets/update-self-1.java +++ /dev/null @@ -1,17 +0,0 @@ - -JSONObject newContent = new JSONObject() - .put("firstname", "My Name Is") - .put("lastname", "Jonas"); - -kuzzle - .updateSelf(newContent, new ResponseListener() { - @Override - public void onSuccess(JSONObject user) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/kuzzle/validate-my-credentials/index.md b/doc/2/core-classes/kuzzle/validate-my-credentials/index.md deleted file mode 100644 index 9c9895e4..00000000 --- a/doc/2/core-classes/kuzzle/validate-my-credentials/index.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -code: true -type: page -title: validateMyCredentials -description: Kuzzle:validateMyCredentials ---- - -# validateMyCredentials - -Update current user's credentials for the specified `strategy`. The credentials to send depend on the authentication plugin and the strategy. - ---- - -## validateMyCredentials(strategy, credentials, [options], callback) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------ | -| `strategy` | string | Strategy you want to create credentials in | -| `credentials` | JSON object | The credentials | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns true or false. - -## Usage - -<<< ./snippets/validate-my-credentials-1.java diff --git a/doc/2/core-classes/kuzzle/validate-my-credentials/snippets/validate-my-credentials-1.java b/doc/2/core-classes/kuzzle/validate-my-credentials/snippets/validate-my-credentials-1.java deleted file mode 100644 index ac12b76d..00000000 --- a/doc/2/core-classes/kuzzle/validate-my-credentials/snippets/validate-my-credentials-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -JSONObject credentials = new JSONObject().put("username", "bar"); - -kuzzle.validateMyCredentials("local", credentials, new ResponseListener() { - @Override - public void onSuccess(Boolean result) { - // result var contains either true or false - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/kuzzle/who-am-i/index.md b/doc/2/core-classes/kuzzle/who-am-i/index.md deleted file mode 100644 index 40993e9c..00000000 --- a/doc/2/core-classes/kuzzle/who-am-i/index.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -code: true -type: page -title: whoAmI -description: Kuzzle:whoAmI ---- - -# whoAmI - -Returns informations about the user who is currently loggedin. - ---- - -## whoAmI(callback) - -| Arguments | Type | Description | -| ---------- | -------- | ------------------------------ | -| `callback` | function | Callback handling the response | - ---- - -## Callback Response - -Returns an instantiated [User](/sdk/java/2/core-classes/user) object. - -## Usage - -<<< ./snippets/who-am-i-1.java diff --git a/doc/2/core-classes/kuzzle/who-am-i/snippets/who-am-i-1.java b/doc/2/core-classes/kuzzle/who-am-i/snippets/who-am-i-1.java deleted file mode 100644 index 5791fefe..00000000 --- a/doc/2/core-classes/kuzzle/who-am-i/snippets/who-am-i-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.whoAmI(new ResponseListener() { - @Override - public void onSuccess(User myself) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/memory-storage/append/index.md b/doc/2/core-classes/memory-storage/append/index.md deleted file mode 100644 index b659612f..00000000 --- a/doc/2/core-classes/memory-storage/append/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: append -description: MemoryStorage:append ---- - -# append - -Appends a value to a key. If the key does not exist, it is created. - -[[_Redis documentation_]](https://redis.io/commands/append) - ---- - -## append(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------- | -| `key` | string | Key identifier | -| `value` | string | Value to append to the key | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Return an integer containing the new length of the key's value. - -## Usage - -<<< ./snippets/append-1.java - -> Callback response: - -```json -5 -``` diff --git a/doc/2/core-classes/memory-storage/append/snippets/append-1.java b/doc/2/core-classes/memory-storage/append/snippets/append-1.java deleted file mode 100644 index cc1f2f90..00000000 --- a/doc/2/core-classes/memory-storage/append/snippets/append-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.append("key", "value", new ResponseListener() { - @Override - public void onSuccess(int newLength) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/bitcount/index.md b/doc/2/core-classes/memory-storage/bitcount/index.md deleted file mode 100644 index 821f1306..00000000 --- a/doc/2/core-classes/memory-storage/bitcount/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: bitcount -description: MemoryStorage:bitcount ---- - -# bitcount - -Counts the number of set bits (population counting) in a string. - -[[_Redis documentation_]](https://redis.io/commands/bitcount) - ---- - -## bitcount(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `end` | int | Ending offset | `-1` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `start` | int | Starting offset | `0` | - ---- - -## Callback Response - -Return an integer containing the count of set bits. - -## Usage - -<<< ./snippets/bitcount-1.java - -> Callback response: - -```json -21 -``` diff --git a/doc/2/core-classes/memory-storage/bitcount/snippets/bitcount-1.java b/doc/2/core-classes/memory-storage/bitcount/snippets/bitcount-1.java deleted file mode 100644 index 63e750ab..00000000 --- a/doc/2/core-classes/memory-storage/bitcount/snippets/bitcount-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.bitcount("key", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/bitop/index.md b/doc/2/core-classes/memory-storage/bitop/index.md deleted file mode 100644 index 9c506a4c..00000000 --- a/doc/2/core-classes/memory-storage/bitop/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: bitop -description: MemoryStorage:bitop ---- - -# bitop - -Performs a bitwise operation between multiple keys (containing string values) and stores the result in the destination key. - -[[_Redis documentation_]](https://redis.io/commands/bitop) - ---- - -## bitop(key, operation, keys, [options], [callback]) - -| Arguments | Type | Description | -| ----------- | ----------- | --------------------------------------------------------------------------- | -| `key` | string | Destination key identifier | -| `operation` | string | Bitwise operation to perform.
Allowed values: `AND`, `OR`, `XOR`, `NOT` | -| `keys` | array | list of source keys on which the bitwise operation will be applied | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the length of the new key's value. - -## Usage - -<<< ./snippets/bitop-1.java - -> Callback response: - -```json -42 -``` diff --git a/doc/2/core-classes/memory-storage/bitop/snippets/bitop-1.java b/doc/2/core-classes/memory-storage/bitop/snippets/bitop-1.java deleted file mode 100644 index 553bb0c9..00000000 --- a/doc/2/core-classes/memory-storage/bitop/snippets/bitop-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] sourceKeys = {"srckey1", "srckey2", "..."}; - -kuzzle.memoryStorage.bitop("key", "AND", sourceKeys, new ResponseListener() { - @Override - public void onSuccess(int length) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/bitpos/index.md b/doc/2/core-classes/memory-storage/bitpos/index.md deleted file mode 100644 index c00f83e8..00000000 --- a/doc/2/core-classes/memory-storage/bitpos/index.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -code: true -type: page -title: bitpos -description: MemoryStorage:bitpos ---- - -# bitpos - -Returns the position of the first bit set to 1 or 0 in a string, or in a substring. - -[[_Redis documentation_]](https://redis.io/commands/bitpos) - ---- - -## bitpos(key, bit, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------- | -| `key` | string | Key identifier | -| `bit` | int | Bit to search.
Allowed values: `0`, `1` | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `end` | int | Ending offset | `-1` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `start` | int | Starting offset | `0` | - ---- - -## Callback Response - -Returns an integer containing the first position of the searched bit in the string value. - -## Usage - -<<< ./snippets/bitpos-1.java - -> Callback response: - -```json -0 -``` diff --git a/doc/2/core-classes/memory-storage/bitpos/snippets/bitpos-1.java b/doc/2/core-classes/memory-storage/bitpos/snippets/bitpos-1.java deleted file mode 100644 index b3530be9..00000000 --- a/doc/2/core-classes/memory-storage/bitpos/snippets/bitpos-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.bitpos("key", 0, new ResponseListener() { - @Override - public void onSuccess(int position) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/constructor/index.md b/doc/2/core-classes/memory-storage/constructor/index.md deleted file mode 100644 index 01e3d8b5..00000000 --- a/doc/2/core-classes/memory-storage/constructor/index.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -code: true -type: page -title: constructor -description: MemoryStorage:constructor -order: 1 ---- - -# Constructor - -Kuzzle's memory storage is a data store separate from the database layer. -It uses Redis internally, and most of its underlying functions are exposed by Kuzzle. - ---- - -## MemoryStorage(Kuzzle) - -| Arguments | Type | Description | -| --------- | ------ | ------------------------------------------------------------------------ | -| `Kuzzle` | object | An instantiated [Kuzzle](/sdk/java/2/core-classes/kuzzle) SDK object | - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/memory-storage/constructor/snippets/constructor-1.java b/doc/2/core-classes/memory-storage/constructor/snippets/constructor-1.java deleted file mode 100644 index 6981c059..00000000 --- a/doc/2/core-classes/memory-storage/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,6 +0,0 @@ - -// using the static instance -MemoryStorage memoryStorage = kuzzle.memoryStorage; - -// or instantiating a new MemoryStorage object -MemoryStorage memoryStorage = new MemoryStorage(kuzzle); diff --git a/doc/2/core-classes/memory-storage/dbsize/index.md b/doc/2/core-classes/memory-storage/dbsize/index.md deleted file mode 100644 index 0eb8a05e..00000000 --- a/doc/2/core-classes/memory-storage/dbsize/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -code: true -type: page -title: dbsize -description: MemoryStorage:dbsize ---- - -# dbsize - -Returns the number of keys in the application database. - -[[_Redis documentation_]](https://redis.io/commands/dbsize) - ---- - -## dbsize([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of keys in the application database. - -## Usage - -<<< ./snippets/dbsize-1.java - -> Callback response: - -```json -12 -``` diff --git a/doc/2/core-classes/memory-storage/dbsize/snippets/dbsize-1.java b/doc/2/core-classes/memory-storage/dbsize/snippets/dbsize-1.java deleted file mode 100644 index b9ce0ece..00000000 --- a/doc/2/core-classes/memory-storage/dbsize/snippets/dbsize-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.dbsize(new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/decr/index.md b/doc/2/core-classes/memory-storage/decr/index.md deleted file mode 100644 index 6ff01cf7..00000000 --- a/doc/2/core-classes/memory-storage/decr/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -code: true -type: page -title: decr -description: MemoryStorage:decr ---- - -# decr - -Decrements the number stored at `key` by 1. If the key does not exist, it is set to 0 before performing the operation. - -[[_Redis documentation_]](https://redis.io/commands/decr) - ---- - -## decr(key, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated key value. - -## Usage - -<<< ./snippets/decr-1.java - -> Callback response: - -```json --1 -``` diff --git a/doc/2/core-classes/memory-storage/decr/snippets/decr-1.java b/doc/2/core-classes/memory-storage/decr/snippets/decr-1.java deleted file mode 100644 index 75ea5d99..00000000 --- a/doc/2/core-classes/memory-storage/decr/snippets/decr-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.decr("key", new ResponseListener() { - @Override - public void onSuccess(int value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/decrby/index.md b/doc/2/core-classes/memory-storage/decrby/index.md deleted file mode 100644 index 8660e4c6..00000000 --- a/doc/2/core-classes/memory-storage/decrby/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: decrby -description: MemoryStorage:decrby ---- - -# decrby - -Decrements the number stored at `key` by a provided integer value. If the key does not exist, it is set to 0 before performing the operation. - -[[_Redis documentation_]](https://redis.io/commands/decrby) - ---- - -## decrby(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `value` | int | Decrement value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated key value. - -## Usage - -<<< ./snippets/decrby-1.java - -> Callback response: - -```json -57 -``` diff --git a/doc/2/core-classes/memory-storage/decrby/snippets/decrby-1.java b/doc/2/core-classes/memory-storage/decrby/snippets/decrby-1.java deleted file mode 100644 index cafa6531..00000000 --- a/doc/2/core-classes/memory-storage/decrby/snippets/decrby-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.decrby("key", 42, new ResponseListener() { - @Override - public void onSuccess(int value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/del/index.md b/doc/2/core-classes/memory-storage/del/index.md deleted file mode 100644 index 79412408..00000000 --- a/doc/2/core-classes/memory-storage/del/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -code: true -type: page -title: del -description: MemoryStorage:del ---- - -# del - -Deletes a list of keys. - -[[_Redis documentation_]](https://redis.io/commands/del) - ---- - -## del(keys, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------- | -| `keys` | array | List of keys to delete | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Return an integer containing the number of deleted keys. - -## Usage - -<<< ./snippets/del-1.java - -> Callback response: - -```json -3 -``` diff --git a/doc/2/core-classes/memory-storage/del/snippets/del-1.java b/doc/2/core-classes/memory-storage/del/snippets/del-1.java deleted file mode 100644 index 2d794978..00000000 --- a/doc/2/core-classes/memory-storage/del/snippets/del-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = {"key1", "key2", "..."}; - -kuzzle.memoryStorage.del(keys, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/exists/index.md b/doc/2/core-classes/memory-storage/exists/index.md deleted file mode 100644 index 06f5b620..00000000 --- a/doc/2/core-classes/memory-storage/exists/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: exists -description: MemoryStorage:exists ---- - -# exists - -Checks if the specified keys exist in the database. - -[[_Redis documentation_]](https://redis.io/commands/exists) - ---- - -## exists(keys, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------- | -| `keys` | array | List of keys to check for existence | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of existing keys amongst the provided list. - -## Usage - -<<< ./snippets/exists-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/exists/snippets/exists-1.java b/doc/2/core-classes/memory-storage/exists/snippets/exists-1.java deleted file mode 100644 index adc33cdb..00000000 --- a/doc/2/core-classes/memory-storage/exists/snippets/exists-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = {"key1", "key2", "..."}; - -kuzzle.memoryStorage.exists(keys, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/expire/index.md b/doc/2/core-classes/memory-storage/expire/index.md deleted file mode 100644 index aecf35af..00000000 --- a/doc/2/core-classes/memory-storage/expire/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: expire -description: MemoryStorage:expire ---- - -# expire - -Sets a timeout (in seconds) on a key. After the timeout has expired, the key will automatically be deleted. - -[[_Redis documentation_]](https://redis.io/commands/expire) - ---- - -## expire(key, seconds, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------ | -| `key` | string | Key identifier | -| `seconds` | int | Time to live, in seconds | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/expire-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/expire/snippets/expire-1.java b/doc/2/core-classes/memory-storage/expire/snippets/expire-1.java deleted file mode 100644 index c4d856bf..00000000 --- a/doc/2/core-classes/memory-storage/expire/snippets/expire-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.expire("key", 42, new ResponseListener() { - @Override - public void onSuccess(int status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/expireat/index.md b/doc/2/core-classes/memory-storage/expireat/index.md deleted file mode 100644 index 7f65f5de..00000000 --- a/doc/2/core-classes/memory-storage/expireat/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: expireat -description: MemoryStorage:expireat ---- - -# expireat - -Sets an expiration timestamp on a key. After the timestamp has been reached, the key will automatically be deleted. -The `timestamp` parameter accepts an [Epoch time](https://en.wikipedia.org/wiki/Unix_time) value. - -[[_Redis documentation_]](https://redis.io/commands/expireat) - ---- - -## expireat(key, timestamp, [options], [callback]) - -| Arguments | Type | Description | -| ----------- | ----------- | -------------------- | -| `key` | string | Key identifier | -| `timestamp` | int | Expiration timestamp | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/expireat-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/expireat/snippets/expireat-1.java b/doc/2/core-classes/memory-storage/expireat/snippets/expireat-1.java deleted file mode 100644 index efc2d90c..00000000 --- a/doc/2/core-classes/memory-storage/expireat/snippets/expireat-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.expireat("key", 1488372354, new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/flushdb/index.md b/doc/2/core-classes/memory-storage/flushdb/index.md deleted file mode 100644 index 4afac997..00000000 --- a/doc/2/core-classes/memory-storage/flushdb/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -code: true -type: page -title: flushdb -description: MemoryStorage:flushdb ---- - -# flushdb - -Deletes all the keys of the database dedicated to client applications (the reserved space for Kuzzle is unaffected). - -[[_Redis documentation_]](https://redis.io/commands/flushdb) - ---- - -## flushdb([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/flushdb-1.java diff --git a/doc/2/core-classes/memory-storage/flushdb/snippets/flushdb-1.java b/doc/2/core-classes/memory-storage/flushdb/snippets/flushdb-1.java deleted file mode 100644 index 84aad814..00000000 --- a/doc/2/core-classes/memory-storage/flushdb/snippets/flushdb-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.flushdb(new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/geoadd/index.md b/doc/2/core-classes/memory-storage/geoadd/index.md deleted file mode 100644 index f6969d46..00000000 --- a/doc/2/core-classes/memory-storage/geoadd/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: geoadd -description: MemoryStorage:geoadd ---- - -# geoadd - -Adds geospatial points to the specified key. - -[[_Redis documentation_]](https://redis.io/commands/geoadd) - ---- - -## geoadd(key, points, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `key` | string | Destination key identifier | -| `points` | array of objects | List of geospatial points to add. Each point is described by a JSON object containing the following properties:
`lon` (longitude, `float`), `lat` (latitude, `float`), `name` (point identifier, `string`) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of points added to the key. - -## Usage - -<<< ./snippets/geoadd-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/geoadd/snippets/geoadd-1.java b/doc/2/core-classes/memory-storage/geoadd/snippets/geoadd-1.java deleted file mode 100644 index 1518772c..00000000 --- a/doc/2/core-classes/memory-storage/geoadd/snippets/geoadd-1.java +++ /dev/null @@ -1,22 +0,0 @@ - -JSONObject[] points = new JSONObject[]{ - new JSONObject() - .put("lon", 13.361389) - .put("lat", 38.115556) - .put("name", "Palermo"), - new JSONObject() - .put("lon", 15.087269) - .put("lat", 37.502669) - .put("name", "Catania") -}; - -kuzzle.memoryStorage.geoadd("key", points, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/geodist/index.md b/doc/2/core-classes/memory-storage/geodist/index.md deleted file mode 100644 index 4929ef11..00000000 --- a/doc/2/core-classes/memory-storage/geodist/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: geodist -description: MemoryStorage:geodist ---- - -# geodist - -Returns the distance between two geospatial members of a key (see [geoadd](/sdk/java/2/core-classes/memory-storage/geoadd)). -The returned distance is expressed in meters by default. - -[[_Redis documentation_]](https://redis.io/commands/geodist) - ---- - -## geodist(key, member1, member2, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------- | -| `key` | string | Key identifier | -| `member1` | string | Name of the first geospatial point | -| `member2` | string | Name of the second geospatial point | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `unit` | string | Distance unit.
Allowed values: `m`, `km`, `mi`, `ft` | `m` | - ---- - -## Callback Response - -Returns the calculated distance between the two provided geospatial points. - -## Usage - -<<< ./snippets/geodist-1.java - -> Callback response: - -```json -166274.1516 -``` diff --git a/doc/2/core-classes/memory-storage/geodist/snippets/geodist-1.java b/doc/2/core-classes/memory-storage/geodist/snippets/geodist-1.java deleted file mode 100644 index b92bbc96..00000000 --- a/doc/2/core-classes/memory-storage/geodist/snippets/geodist-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.geodist("key", "Palermo", "Catania", new ResponseListener() { - @Override - public void onSuccess(double distance) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/geohash/index.md b/doc/2/core-classes/memory-storage/geohash/index.md deleted file mode 100644 index 71725fc0..00000000 --- a/doc/2/core-classes/memory-storage/geohash/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: geohash -description: MemoryStorage:geohash ---- - -# geohash - -Returns a valid [geohash](https://en.wikipedia.org/wiki/Geohash) for the provided key's members (see [geoadd](/sdk/java/2/core-classes/memory-storage/geoadd)). - -[[_Redis documentation_]](https://redis.io/commands/geohash) - ---- - -## geohash(key, members, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------------------- | -| `key` | string | Key identifier | -| `members` | array | List of geospatial points contained in the key | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of geohashes, in the same order than the provided members list. - -## Usage - -<<< ./snippets/geohash-1.java - -> Callback response: - -```json -["sqc8b49rny0", "sqdtr74hyu0"] -``` diff --git a/doc/2/core-classes/memory-storage/geohash/snippets/geohash-1.java b/doc/2/core-classes/memory-storage/geohash/snippets/geohash-1.java deleted file mode 100644 index 2e61ffce..00000000 --- a/doc/2/core-classes/memory-storage/geohash/snippets/geohash-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] members = {"Palermo", "Catania"}; - -kuzzle.memoryStorage.geohash("key", members, new ResponseListener() { - @Override - public void onSuccess(String[] hashes) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/geopos/index.md b/doc/2/core-classes/memory-storage/geopos/index.md deleted file mode 100644 index 95ccffc9..00000000 --- a/doc/2/core-classes/memory-storage/geopos/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: geopos -description: MemoryStorage:geopos ---- - -# geopos - -Returns the positions (longitude, latitude) of the provided key's members (see [geoadd](/sdk/java/2/core-classes/memory-storage/geoadd)). - -[[_Redis documentation_]](https://redis.io/commands/geopos) - ---- - -## geopos(key, members, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------------------- | -| `key` | string | Key identifier | -| `members` | array | List of geospatial points contained in the key | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of longitude-latitude pairs, in the same order as the provided members list. - -## Usage - -<<< ./snippets/geopos-1.java - -> Callback response: - -```json -[[13.361389, 38.115556], [15.087269, 37.502669]] -``` diff --git a/doc/2/core-classes/memory-storage/geopos/snippets/geopos-1.java b/doc/2/core-classes/memory-storage/geopos/snippets/geopos-1.java deleted file mode 100644 index 7006869c..00000000 --- a/doc/2/core-classes/memory-storage/geopos/snippets/geopos-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] members = {"Palermo", "Catania"}; - -kuzzle.memoryStorage.geopos("key", members, new ResponseListener() { - @Override - public void onSuccess(Double[][] positions) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/georadius/index.md b/doc/2/core-classes/memory-storage/georadius/index.md deleted file mode 100644 index 7769625f..00000000 --- a/doc/2/core-classes/memory-storage/georadius/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -code: true -type: page -title: georadius -description: MemoryStorage:georadius ---- - -# georadius - -> Callback response, with no option provided: - -```json -[{ "name": "Palermo" }, { "name": "Catania" }] -``` - -> Callback response, with the "withcoord" option: - -```json -[ - { "name": "Palermo", "coordinates": [13.361389338970184, 38.1155563954963] }, - { "name": "Catania", "coordinates": [15.087267458438873, 37.50266842333162] } -] -``` - -> Callback response, with the "withdist" option: - -```json -[ - { "name": "Palermo", "distance": 190.4424 }, - { "name": "Catania", "distance": 56.4413 } -] -``` - -Returns the members (added with [geoadd](/sdk/java/2/core-classes/memory-storage/geoadd)) of a given key inside the provided geospatial radius. - -[[_Redis documentation_]](https://redis.io/commands/georadius) - ---- - -## georadius(key, longitude, latitude, distance, unit, [options], callback) - -| Arguments | Type | Description | -| ----------- | ----------- | ------------------------------------- | -| `key` | string | Key identifier | -| `longitude` | double | Longitude of the center of the radius | -| `latitude` | double | Latitude of the center of the radius | -| `distance` | double | Maximum distance from the center | -| `unit` | string | Distance unit | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | ------- | -| `count` | int | Limit the result set to `count` members | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `sort` | string | Return items from the nearest to the farthest to the center (`ASC`) or vice versa (`DESC`) | `null` | -| `withcoord` | boolean | Also return the longitude and latitude coordinates of the matching items | `false` | -| `withdist` | boolean | Also return the distance of the returned items from the specified center, in the same unit than the one provided with `unit` | `false` | - ---- - -## Callback Response - -Returns an array of names for points that are inside the provided radius. - -## Usage - -<<< ./snippets/georadius-1.java diff --git a/doc/2/core-classes/memory-storage/georadius/snippets/georadius-1.java b/doc/2/core-classes/memory-storage/georadius/snippets/georadius-1.java deleted file mode 100644 index c5a3b092..00000000 --- a/doc/2/core-classes/memory-storage/georadius/snippets/georadius-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.georadius("key", 15, 37, 200, "km", new ResponseListener() { - @Override - public void onSuccess(JSONObject[] points) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/georadiusbymember/index.md b/doc/2/core-classes/memory-storage/georadiusbymember/index.md deleted file mode 100644 index 98a4cc1b..00000000 --- a/doc/2/core-classes/memory-storage/georadiusbymember/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -code: true -type: page -title: georadiusbymember -description: MemoryStorage:georadiusbymember ---- - -# georadiusbymember - -> Callback response, with the "withcoord" option: - -```json -[ - { "name": "Palermo", "coordinates": [13.361389338970184, 38.1155563954963] }, - { "name": "Catania", "coordinates": [15.087267458438873, 37.50266842333162] } -] -``` - -> Callback response, with the "withdist" option: - -```json -[ - { "name": "Palermo", "distance": 190.4424 }, - { "name": "Catania", "distance": 56.4413 } -] -``` - -Returns the members (added with [geoadd](/sdk/java/2/core-classes/memory-storage/geoadd)) of a given key inside the provided geospatial radius, centered around one of a key's member. -[[_Redis documentation_]](https://redis.io/commands/georadiusbymember) - ---- - -## georadiusbymember(key, member, distance, unit, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------------------------- | -| `key` | string | Key identifier | -| `member` | string | Name of the point to use as the center of the radius | -| `distance` | double | Maximum distance from the center | -| `unit` | string | Distance unit | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | ------- | -| `count` | int | Limit the result set to `count` members | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `sort` | string | Return items from the nearest to the farthest to the center (`ASC`) or vice versa (`DESC`) | `null` | -| `withcoord` | boolean | Also return the longitude and latitude coordinates of the matching items | `false` | -| `withdist` | boolean | Also return the distance of the returned items from the specified center, in the same unit than the one provided with `unit` | `false` | - ---- - -## Callback Response - -Returns an array of names for points that are inside the provided radius. - -## Usage - -<<< ./snippets/georadiusbymember-1.java - -> Callback response: - -```json -[{ "name": "Palermo" }, { "name": "Catania" }] -``` diff --git a/doc/2/core-classes/memory-storage/georadiusbymember/snippets/georadiusbymember-1.java b/doc/2/core-classes/memory-storage/georadiusbymember/snippets/georadiusbymember-1.java deleted file mode 100644 index 92800702..00000000 --- a/doc/2/core-classes/memory-storage/georadiusbymember/snippets/georadiusbymember-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.georadiusbymember("key", "Palermo", 200, "km", new ResponseListener() { - @Override - public void onSuccess(JSONObject[] points) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/get/index.md b/doc/2/core-classes/memory-storage/get/index.md deleted file mode 100644 index 83e3c259..00000000 --- a/doc/2/core-classes/memory-storage/get/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: get -description: MemoryStorage:get ---- - -# get - -Returns the value of a key, or null if the key doesn’t exist. - -[[_Redis documentation_]](https://redis.io/commands/get) - ---- - -## get(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the key's value. - -## Usage - -<<< ./snippets/get-1.java - -> Callback response: - -```json -"value" -``` diff --git a/doc/2/core-classes/memory-storage/get/snippets/get-1.java b/doc/2/core-classes/memory-storage/get/snippets/get-1.java deleted file mode 100644 index 5276938d..00000000 --- a/doc/2/core-classes/memory-storage/get/snippets/get-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.get("key", new ResponseListener() { - @Override - public void onSuccess(String value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/getbit/index.md b/doc/2/core-classes/memory-storage/getbit/index.md deleted file mode 100644 index b3b365e5..00000000 --- a/doc/2/core-classes/memory-storage/getbit/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: getbit -description: MemoryStorage:getbit ---- - -# getbit - -Returns the bit value at `offset`, in the string value stored in a key. - -[[_Redis documentation_]](https://redis.io/commands/getbit) - ---- - -## getbit(key, offset, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------- | -| `key` | string | Key identifier | -| `offset` | int | Offset position in the key's value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the bit value at the provided offset. - -## Usage - -<<< ./snippets/getbit-1.java - -> Callback response: - -```json -1 -``` diff --git a/doc/2/core-classes/memory-storage/getbit/snippets/getbit-1.java b/doc/2/core-classes/memory-storage/getbit/snippets/getbit-1.java deleted file mode 100644 index baa80a5f..00000000 --- a/doc/2/core-classes/memory-storage/getbit/snippets/getbit-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.getbit("key", 10, new ResponseListener() { - @Override - public void onSuccess(int bit) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/getrange/index.md b/doc/2/core-classes/memory-storage/getrange/index.md deleted file mode 100644 index 3a5881aa..00000000 --- a/doc/2/core-classes/memory-storage/getrange/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: getrange -description: MemoryStorage:getrange ---- - -# getrange - -Returns a substring of a key's value (index starts at position `0`). - -[[_Redis documentation_]](https://redis.io/commands/getrange) - ---- - -## getrange(key, start, end, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `start` | int | Starting index | -| `end` | int | Ending index | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a substring of the key's value. - -## Usage - -<<< ./snippets/getrange-1.java - -> Callback response: - -```json -"lue" -``` diff --git a/doc/2/core-classes/memory-storage/getrange/snippets/getrange-1.java b/doc/2/core-classes/memory-storage/getrange/snippets/getrange-1.java deleted file mode 100644 index 1fff31f6..00000000 --- a/doc/2/core-classes/memory-storage/getrange/snippets/getrange-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.getrange("key", 2, 4, new ResponseListener() { - @Override - public void onSuccess(String value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/getset/index.md b/doc/2/core-classes/memory-storage/getset/index.md deleted file mode 100644 index 72b34b5a..00000000 --- a/doc/2/core-classes/memory-storage/getset/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: getset -description: MemoryStorage:getset ---- - -# getset - -Sets a new value for a key and returns its previous value. - -[[_Redis documentation_]](https://redis.io/commands/getset) - ---- - -## getset(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `value` | string | Key's new value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns the key's previous value. - -## Usage - -<<< ./snippets/getset-1.java - -> Callback response: - -```json -"value" -``` diff --git a/doc/2/core-classes/memory-storage/getset/snippets/getset-1.java b/doc/2/core-classes/memory-storage/getset/snippets/getset-1.java deleted file mode 100644 index 8af9bfb0..00000000 --- a/doc/2/core-classes/memory-storage/getset/snippets/getset-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.getset("key", "new value", new ResponseListener() { - @Override - public void onSuccess(String oldValue) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hdel/index.md b/doc/2/core-classes/memory-storage/hdel/index.md deleted file mode 100644 index f94901c7..00000000 --- a/doc/2/core-classes/memory-storage/hdel/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: hdel -description: MemoryStorage:hdel ---- - -# hdel - -Removes fields from a hash. - -[[_Redis documentation_]](https://redis.io/commands/hdel) - ---- - -## hdel(key, fields, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------- | -| `key` | string | Key identifier | -| `fields` | array | List of field names to delete | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns the number of removed fields. - -## Usage - -<<< ./snippets/hdel-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/hdel/snippets/hdel-1.java b/doc/2/core-classes/memory-storage/hdel/snippets/hdel-1.java deleted file mode 100644 index 8d389fad..00000000 --- a/doc/2/core-classes/memory-storage/hdel/snippets/hdel-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] fields = {"field1", "field2", "..."}; - -kuzzle.memoryStorage.hdel("key", fields, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hexists/index.md b/doc/2/core-classes/memory-storage/hexists/index.md deleted file mode 100644 index 19b85b8e..00000000 --- a/doc/2/core-classes/memory-storage/hexists/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: hexists -description: MemoryStorage:hexists ---- - -# hexists - -Checks if a field exists in a hash. - -[[_Redis documentation_]](https://redis.io/commands/hexists) - ---- - -## hexists(key, field, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `field` | string | Field name | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -A boolean value specifying if the field exists or not. - -## Usage - -<<< ./snippets/hexists-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/hexists/snippets/hexists-1.java b/doc/2/core-classes/memory-storage/hexists/snippets/hexists-1.java deleted file mode 100644 index d17b3476..00000000 --- a/doc/2/core-classes/memory-storage/hexists/snippets/hexists-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hexists("key", "field1", new ResponseListener() { - @Override - public void onSuccess(Boolean exists) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hget/index.md b/doc/2/core-classes/memory-storage/hget/index.md deleted file mode 100644 index 0b828851..00000000 --- a/doc/2/core-classes/memory-storage/hget/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: hget -description: MemoryStorage:hget ---- - -# hget - -Returns the field’s value of a hash. - -[[_Redis documentation_]](https://redis.io/commands/hget) - ---- - -## hget(key, field, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `field` | string | Field name | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the requested field's value. - -## Usage - -<<< ./snippets/hget-1.java - -> Callback response: - -```json -"foo" -``` diff --git a/doc/2/core-classes/memory-storage/hget/snippets/hget-1.java b/doc/2/core-classes/memory-storage/hget/snippets/hget-1.java deleted file mode 100644 index c10baa00..00000000 --- a/doc/2/core-classes/memory-storage/hget/snippets/hget-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hget("key", "field1", new ResponseListener() { - @Override - public void onSuccess(String value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hgetall/index.md b/doc/2/core-classes/memory-storage/hgetall/index.md deleted file mode 100644 index dd1eee7c..00000000 --- a/doc/2/core-classes/memory-storage/hgetall/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: hgetall -description: MemoryStorage:hgetall ---- - -# hgetall - -Returns all fields and values of a hash. - -[[_Redis documentation_]](https://redis.io/commands/hgetall) - ---- - -## hgetall(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a JSON object containing the fields and values of a hash. - -## Usage - -<<< ./snippets/hgetall-1.java - -> Callback response: - -```json -{ - "field1": "value", - "field2": "value", - "...": "..." -} -``` diff --git a/doc/2/core-classes/memory-storage/hgetall/snippets/hgetall-1.java b/doc/2/core-classes/memory-storage/hgetall/snippets/hgetall-1.java deleted file mode 100644 index f027e1cf..00000000 --- a/doc/2/core-classes/memory-storage/hgetall/snippets/hgetall-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hgetall("key", new ResponseListener() { - @Override - public void onSuccess(JSONObject hash) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hincrby/index.md b/doc/2/core-classes/memory-storage/hincrby/index.md deleted file mode 100644 index 62f82202..00000000 --- a/doc/2/core-classes/memory-storage/hincrby/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: hincrby -description: MemoryStorage:hincrby ---- - -# hincrby - -Increments the number stored in a hash field by the provided integer value. - -[[_Redis documentation_]](https://redis.io/commands/hincrby) - ---- - -## hincrby(key, field, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------- | -| `key` | string | Key identifier | -| `field` | string | Hash field to increment | -| `value` | int | Increment value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns the newly incremented value. - -## Usage - -<<< ./snippets/hincrby-1.java - -> Callback response: - -```json -45 -``` diff --git a/doc/2/core-classes/memory-storage/hincrby/snippets/hincrby-1.java b/doc/2/core-classes/memory-storage/hincrby/snippets/hincrby-1.java deleted file mode 100644 index 22ca764a..00000000 --- a/doc/2/core-classes/memory-storage/hincrby/snippets/hincrby-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hincrby("key", "field", 42, new ResponseListener() { - @Override - public void onSuccess(int value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hincrbyfloat/index.md b/doc/2/core-classes/memory-storage/hincrbyfloat/index.md deleted file mode 100644 index 1afa2f1b..00000000 --- a/doc/2/core-classes/memory-storage/hincrbyfloat/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: hincrbyfloat -description: MemoryStorage:hincrbyfloat ---- - -# hincrbyfloat - -Increments the number stored in a hash field by the provided float value. - -[[_Redis documentation_]](https://redis.io/commands/hincrbyfloat) - ---- - -## hincrbyfloat(key, field, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------- | -| `key` | string | Key identifier | -| `field` | string | Hash field to increment | -| `value` | double | Increment value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns the newly incremented value, as a floating point number. - -## Usage - -<<< ./snippets/hincrbyfloat-1.java - -> Callback response: - -```json -48.14159 -``` diff --git a/doc/2/core-classes/memory-storage/hincrbyfloat/snippets/hincrbyfloat-1.java b/doc/2/core-classes/memory-storage/hincrbyfloat/snippets/hincrbyfloat-1.java deleted file mode 100644 index 4f3a0745..00000000 --- a/doc/2/core-classes/memory-storage/hincrbyfloat/snippets/hincrbyfloat-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hincrbyfloat("key", "field", 3.14159, new ResponseListener() { - @Override - public void onSuccess(int value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hkeys/index.md b/doc/2/core-classes/memory-storage/hkeys/index.md deleted file mode 100644 index ef9210c5..00000000 --- a/doc/2/core-classes/memory-storage/hkeys/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: hkeys -description: MemoryStorage:hkeys ---- - -# hkeys - -Returns all field names contained in a hash. - -[[_Redis documentation_]](https://redis.io/commands/hkeys) - ---- - -## hkeys(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of field names. - -## Usage - -<<< ./snippets/hkeys-1.java - -> Callback response: - -```json -["field1", "field2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/hkeys/snippets/hkeys-1.java b/doc/2/core-classes/memory-storage/hkeys/snippets/hkeys-1.java deleted file mode 100644 index 75d69ed6..00000000 --- a/doc/2/core-classes/memory-storage/hkeys/snippets/hkeys-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hkeys("key", new ResponseListener() { - @Override - public void onSuccess(String[] fields) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hlen/index.md b/doc/2/core-classes/memory-storage/hlen/index.md deleted file mode 100644 index 06013547..00000000 --- a/doc/2/core-classes/memory-storage/hlen/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: hlen -description: MemoryStorage:hlen ---- - -# hlen - -Returns the number of fields contained in a hash. - -[[_Redis documentation_]](https://redis.io/commands/hlen) - ---- - -## hlen(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of fields in the hash. - -## Usage - -<<< ./snippets/hlen-1.java - -> Callback response: - -```json -13 -``` diff --git a/doc/2/core-classes/memory-storage/hlen/snippets/hlen-1.java b/doc/2/core-classes/memory-storage/hlen/snippets/hlen-1.java deleted file mode 100644 index e4ce5135..00000000 --- a/doc/2/core-classes/memory-storage/hlen/snippets/hlen-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hlen("key", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hmget/index.md b/doc/2/core-classes/memory-storage/hmget/index.md deleted file mode 100644 index a624abe0..00000000 --- a/doc/2/core-classes/memory-storage/hmget/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: hmget -description: MemoryStorage:hmget ---- - -# hmget - -Returns the values of the specified hash’s fields. - -[[_Redis documentation_]](https://redis.io/commands/hmget) - ---- - -## hmget(key, fields, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------- | -| `key` | string | Key identifier | -| `fields` | array | List of fields to examine | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array containing the specified fields values. - -## Usage - -<<< ./snippets/hmget-1.java - -> Callback response: - -```json -["field1's value", "field2's value", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/hmget/snippets/hmget-1.java b/doc/2/core-classes/memory-storage/hmget/snippets/hmget-1.java deleted file mode 100644 index 54892193..00000000 --- a/doc/2/core-classes/memory-storage/hmget/snippets/hmget-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] fields = {"field1", "field2"}; - -kuzzle.memoryStorage.hmget("key", fields, new ResponseListener() { - @Override - public void onSuccess(String[] values) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hmset/index.md b/doc/2/core-classes/memory-storage/hmset/index.md deleted file mode 100644 index f8d0a8cf..00000000 --- a/doc/2/core-classes/memory-storage/hmset/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: hmset -description: MemoryStorage:hmset ---- - -# hmset - -Sets multiple fields at once in a hash. - -[[_Redis documentation_]](https://redis.io/commands/hmset) - ---- - -## hmset(key, entries, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `key` | string | Key identifier | -| `entries` | array | List of fields to add, with their value. Each entry is described by a JSON object containing the following properties:
`field` (field name), `value` (field's value) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/hmset-1.java diff --git a/doc/2/core-classes/memory-storage/hmset/snippets/hmset-1.java b/doc/2/core-classes/memory-storage/hmset/snippets/hmset-1.java deleted file mode 100644 index d0937992..00000000 --- a/doc/2/core-classes/memory-storage/hmset/snippets/hmset-1.java +++ /dev/null @@ -1,17 +0,0 @@ - -JSONObject[] entries = new JSONObject[]{ - new JSONObject().put("field", "field1").put("value", "foo"), - new JSONObject().put("field", "field2").put("value", "bar"), - new JSONObject().put("field", "...").put("value", "...") -}; - -kuzzle.memoryStorage.hmset("key", entries, new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hscan/index.md b/doc/2/core-classes/memory-storage/hscan/index.md deleted file mode 100644 index 57036174..00000000 --- a/doc/2/core-classes/memory-storage/hscan/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: hscan -description: MemoryStorage:hscan ---- - -# hscan - -Identical to [scan](/sdk/java/2/core-classes/memory-storage/scan), except that `hscan` iterates over the fields contained in a hash. - -[[_Redis documentation_]](https://redis.io/commands/hscan) - ---- - -## hscan(key, cursor, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------- | -| `key` | string | Key identifier | -| `cursor` | int | Page number (iteration starts with a cursor value of `0`, and ends when the next cursor position is `0`) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------------------------------------- | ------- | -| `count` | int | Return the _approximate_ `count` number of items per result page | `10` | -| `match` | string | Search only for field names matching the provided pattern | `*` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object containing 2 entries: - -- the cursor position for the next page of results (a next position of `0` indicates the end of the scan) -- an array of field names and values - -## Usage - -<<< ./snippets/hscan-1.java - -> Callback response: - -```json -{ - "cursor": 18, - "values": ["field1", "field1 value", "field2", "field2 value"] -} -``` diff --git a/doc/2/core-classes/memory-storage/hscan/snippets/hscan-1.java b/doc/2/core-classes/memory-storage/hscan/snippets/hscan-1.java deleted file mode 100644 index 9e1ea9a5..00000000 --- a/doc/2/core-classes/memory-storage/hscan/snippets/hscan-1.java +++ /dev/null @@ -1,10 +0,0 @@ - -kuzzle.memoryStorage.hscan("key", 0, new ResponseListener() { - @Override - public void onSuccess(JSONObject page) { - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hset/index.md b/doc/2/core-classes/memory-storage/hset/index.md deleted file mode 100644 index 1e98396f..00000000 --- a/doc/2/core-classes/memory-storage/hset/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: hset -description: MemoryStorage:hset ---- - -# hset - -Sets a field and its value in a hash. If the key does not exist, a new key holding a hash is created. If the field already exists, its value is overwritten. - -[[_Redis documentation_]](https://redis.io/commands/hset) - ---- - -## hset(key, field, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------- | -| `key` | string | Key identifier | -| `field` | string | Field name to insert or to update | -| `value` | string | Associated field value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/hset-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/hset/snippets/hset-1.java b/doc/2/core-classes/memory-storage/hset/snippets/hset-1.java deleted file mode 100644 index a8370971..00000000 --- a/doc/2/core-classes/memory-storage/hset/snippets/hset-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hset("key", "field", "value", new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hsetnx/index.md b/doc/2/core-classes/memory-storage/hsetnx/index.md deleted file mode 100644 index 6703e7ed..00000000 --- a/doc/2/core-classes/memory-storage/hsetnx/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: hsetnx -description: MemoryStorage:hsetnx ---- - -# hsetnx - -Sets a field and its value in a hash, only if the field does not already exist. - -[[_Redis documentation_]](https://redis.io/commands/hsetnx) - ---- - -## hsetnx(key, field, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------- | -| `key` | string | Key identifier | -| `field` | string | Field name to insert or to update | -| `value` | string | Associated field value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/hsetnx-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/hsetnx/snippets/hsetnx-1.java b/doc/2/core-classes/memory-storage/hsetnx/snippets/hsetnx-1.java deleted file mode 100644 index 081637ad..00000000 --- a/doc/2/core-classes/memory-storage/hsetnx/snippets/hsetnx-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hsetnx("key", "field", "value", new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hstrlen/index.md b/doc/2/core-classes/memory-storage/hstrlen/index.md deleted file mode 100644 index 04dee2a2..00000000 --- a/doc/2/core-classes/memory-storage/hstrlen/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: hstrlen -description: MemoryStorage:hstrlen ---- - -# hstrlen - -Returns the string length of a field’s value in a hash. - -[[_Redis documentation_]](https://redis.io/commands/hstrlen) - ---- - -## hstrlen(key, field, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `field` | string | Hash field name | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the string length of a field's value. - -## Usage - -<<< ./snippets/hstrlen-1.java - -> Callback response: - -```json -3 -``` diff --git a/doc/2/core-classes/memory-storage/hstrlen/snippets/hstrlen-1.java b/doc/2/core-classes/memory-storage/hstrlen/snippets/hstrlen-1.java deleted file mode 100644 index 50066706..00000000 --- a/doc/2/core-classes/memory-storage/hstrlen/snippets/hstrlen-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hstrlen("key", "field", new ResponseListener() { - @Override - public void onSuccess(int length) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/hvals/index.md b/doc/2/core-classes/memory-storage/hvals/index.md deleted file mode 100644 index 6367c0f0..00000000 --- a/doc/2/core-classes/memory-storage/hvals/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: hvals -description: MemoryStorage:hvals ---- - -# hvals - -Returns all values contained in a hash. - -[[_Redis documentation_]](https://redis.io/commands/hvals) - ---- - -## hvals(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array containing the values of a hash. - -## Usage - -<<< ./snippets/hvals-1.java - -> Callback response: - -```json -["field1's value", "field2's value", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/hvals/snippets/hvals-1.java b/doc/2/core-classes/memory-storage/hvals/snippets/hvals-1.java deleted file mode 100644 index dd80e126..00000000 --- a/doc/2/core-classes/memory-storage/hvals/snippets/hvals-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.hvals("key", new ResponseListener() { - @Override - public void onSuccess(String[] values) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/incr/index.md b/doc/2/core-classes/memory-storage/incr/index.md deleted file mode 100644 index ac70eb95..00000000 --- a/doc/2/core-classes/memory-storage/incr/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -code: true -type: page -title: incr -description: MemoryStorage:incr ---- - -# incr - -Increments the number stored at `key` by 1. If the key does not exist, it is set to 0 before performing the operation. - -[[_Redis documentation_]](https://redis.io/commands/incr) - ---- - -## incr(key, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated key value. - -## Usage - -<<< ./snippets/incr-1.java - -> Callback response: - -```json -42 -``` diff --git a/doc/2/core-classes/memory-storage/incr/snippets/incr-1.java b/doc/2/core-classes/memory-storage/incr/snippets/incr-1.java deleted file mode 100644 index fb046046..00000000 --- a/doc/2/core-classes/memory-storage/incr/snippets/incr-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.incr("key", new ResponseListener() { - @Override - public void onSuccess(int value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/incrby/index.md b/doc/2/core-classes/memory-storage/incrby/index.md deleted file mode 100644 index 53b5dd58..00000000 --- a/doc/2/core-classes/memory-storage/incrby/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: incrby -description: MemoryStorage:incrby ---- - -# incrby - -Increments the number stored at `key` by the provided integer value. If the key does not exist, it is set to 0 before performing the operation. - -[[_Redis documentation_]](https://redis.io/commands/incrby) - ---- - -## incrby(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `value` | int | Increment value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated key value. - -## Usage - -<<< ./snippets/incrby-1.java - -> Callback response: - -```json -39 -``` diff --git a/doc/2/core-classes/memory-storage/incrby/snippets/incrby-1.java b/doc/2/core-classes/memory-storage/incrby/snippets/incrby-1.java deleted file mode 100644 index 172fd4f8..00000000 --- a/doc/2/core-classes/memory-storage/incrby/snippets/incrby-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.incrby("key", -3, new ResponseListener() { - @Override - public void onSuccess(int value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/incrbyfloat/index.md b/doc/2/core-classes/memory-storage/incrbyfloat/index.md deleted file mode 100644 index f6a3812b..00000000 --- a/doc/2/core-classes/memory-storage/incrbyfloat/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: incrbyfloat -description: MemoryStorage:incrbyfloat ---- - -# incrbyfloat - -Increments the number stored at `key` by the provided float value. If the key does not exist, it is set to 0 before performing the operation. - -[[_Redis documentation_]](https://redis.io/commands/incrbyfloat) - ---- - -## incrbyfloat(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `value` | double | Increment value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a floating point number that contains the updated key value. - -## Usage - -<<< ./snippets/incrbyfloat-1.java - -> Callback response: - -```json -38.85841 -``` diff --git a/doc/2/core-classes/memory-storage/incrbyfloat/snippets/incrbyfloat-1.java b/doc/2/core-classes/memory-storage/incrbyfloat/snippets/incrbyfloat-1.java deleted file mode 100644 index cef5c52c..00000000 --- a/doc/2/core-classes/memory-storage/incrbyfloat/snippets/incrbyfloat-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.incrbyfloat("key", -3.14159, new ResponseListener() { - @Override - public void onSuccess(double value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/index.md b/doc/2/core-classes/memory-storage/index.md deleted file mode 100644 index ee4efe41..00000000 --- a/doc/2/core-classes/memory-storage/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: MemoryStorage -description: MemoryStorage documentation ---- diff --git a/doc/2/core-classes/memory-storage/keys/index.md b/doc/2/core-classes/memory-storage/keys/index.md deleted file mode 100644 index 5c0ec55c..00000000 --- a/doc/2/core-classes/memory-storage/keys/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: keys -description: MemoryStorage:keys ---- - -# keys - -Returns all keys matching the provided pattern. - -[[_Redis documentation_]](https://redis.io/commands/keys) - ---- - -## keys(pattern, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------------- | -| `pattern` | string | Pattern used to filter the returned key names | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of key names matching the provided pattern. - -## Usage - -<<< ./snippets/keys-1.java - -> Callback response: - -```json -["foo", "foobar", "foofighters"] -``` diff --git a/doc/2/core-classes/memory-storage/keys/snippets/keys-1.java b/doc/2/core-classes/memory-storage/keys/snippets/keys-1.java deleted file mode 100644 index 2bf4ed77..00000000 --- a/doc/2/core-classes/memory-storage/keys/snippets/keys-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.keys("foo*", new ResponseListener() { - @Override - public void onSuccess(String[] keys) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/lindex/index.md b/doc/2/core-classes/memory-storage/lindex/index.md deleted file mode 100644 index f2ca3b46..00000000 --- a/doc/2/core-classes/memory-storage/lindex/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: lindex -description: MemoryStorage:lindex ---- - -# lindex - -Returns the element at the provided index in a list. - -[[_Redis documentation_]](https://redis.io/commands/lindex) - ---- - -## lindex(key, index, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------- | -| `key` | string | Key identifier | -| `index` | int | Element position in the list | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a string containing the retrieved element's value. - -## Usage - -<<< ./snippets/lindex-1.java - -> Callback response: - -```json -"foo" -``` diff --git a/doc/2/core-classes/memory-storage/lindex/snippets/lindex-1.java b/doc/2/core-classes/memory-storage/lindex/snippets/lindex-1.java deleted file mode 100644 index 863e6b17..00000000 --- a/doc/2/core-classes/memory-storage/lindex/snippets/lindex-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.lindex("key", 3, new ResponseListener() { - @Override - public void onSuccess(String value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/linsert/index.md b/doc/2/core-classes/memory-storage/linsert/index.md deleted file mode 100644 index 8faaa795..00000000 --- a/doc/2/core-classes/memory-storage/linsert/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: linsert -description: MemoryStorage:linsert ---- - -# linsert - -Inserts a value in a list, either before or after the reference pivot value. - -[[_Redis documentation_]](https://redis.io/commands/linsert) - ---- - -## linsert(key, position, pivot, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------------------------------------------------------------------- | -| `key` | string | Key identifier | -| `position` | string | Indicates if the new value is to be inserted before or after the pivot value.
Allowed values: `before`, `after` | -| `pivot` | string | Pivot value used as a point of reference in the list | -| `value` | string | The value to insert | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated number of items in the list. - -## Usage - -<<< ./snippets/linsert-1.java - -> Callback response: - -```json -4 -``` diff --git a/doc/2/core-classes/memory-storage/linsert/snippets/linsert-1.java b/doc/2/core-classes/memory-storage/linsert/snippets/linsert-1.java deleted file mode 100644 index bf3fa46e..00000000 --- a/doc/2/core-classes/memory-storage/linsert/snippets/linsert-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.linsert("key", "after", "foo", "bar", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/llen/index.md b/doc/2/core-classes/memory-storage/llen/index.md deleted file mode 100644 index 9636d997..00000000 --- a/doc/2/core-classes/memory-storage/llen/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: llen -description: MemoryStorage:llen ---- - -# llen - -Counts the number of items in a list. - -[[_Redis documentation_]](https://redis.io/commands/llen) - ---- - -## llen(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of items of a list. - -## Usage - -<<< ./snippets/llen-1.java - -> Callback response: - -```json -3 -``` diff --git a/doc/2/core-classes/memory-storage/llen/snippets/llen-1.java b/doc/2/core-classes/memory-storage/llen/snippets/llen-1.java deleted file mode 100644 index 42acb4ee..00000000 --- a/doc/2/core-classes/memory-storage/llen/snippets/llen-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.llen("key", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/lpop/index.md b/doc/2/core-classes/memory-storage/lpop/index.md deleted file mode 100644 index 8fa4c5b8..00000000 --- a/doc/2/core-classes/memory-storage/lpop/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -code: true -type: page -title: lpop -description: MemoryStorage:lpop ---- - -# lpop - -Removes and returns the first element of a list. - -[[_Redis documentation_]](https://redis.io/commands/lpop) - ---- - -## lpop(key, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns the value of the removed item. - -## Usage - -<<< ./snippets/lpop-1.java - -> Callback response: - -```json -"foo" -``` diff --git a/doc/2/core-classes/memory-storage/lpop/snippets/lpop-1.java b/doc/2/core-classes/memory-storage/lpop/snippets/lpop-1.java deleted file mode 100644 index d3889f55..00000000 --- a/doc/2/core-classes/memory-storage/lpop/snippets/lpop-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.lpop("key", new ResponseListener() { - @Override - public void onSuccess(String value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/lpush/index.md b/doc/2/core-classes/memory-storage/lpush/index.md deleted file mode 100644 index e736aa46..00000000 --- a/doc/2/core-classes/memory-storage/lpush/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -code: true -type: page -title: lpush -description: MemoryStorage:lpush ---- - -# lpush - -Prepends the specified values to a list. If the key does not exist, it is created holding an empty list before performing the operation. - -[[_Redis documentation_]](https://redis.io/commands/lpush) - ---- - -## lpush(key, values, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------ | -| `key` | string | Key identifier | -| `values` | array | Values to add at the beginning of the list | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated number of items in the list. - -## Usage - -<<< ./snippets/lpush-1.java - -> Callback response: - -```json -6 -``` diff --git a/doc/2/core-classes/memory-storage/lpush/snippets/lpush-1.java b/doc/2/core-classes/memory-storage/lpush/snippets/lpush-1.java deleted file mode 100644 index 00257b45..00000000 --- a/doc/2/core-classes/memory-storage/lpush/snippets/lpush-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] items = new String[]{"foo", "bar", "baz"}; - -kuzzle.memoryStorage.lpush("key", items, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/lpushx/index.md b/doc/2/core-classes/memory-storage/lpushx/index.md deleted file mode 100644 index 166f0fc5..00000000 --- a/doc/2/core-classes/memory-storage/lpushx/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: lpushx -description: MemoryStorage:lpushx ---- - -# lpushx - -Prepends the specified value to a list, only if the key already exists and if it holds a list. - -[[_Redis documentation_]](https://redis.io/commands/lpushx) - ---- - -## lpushx(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `key` | string | Key identifier | -| `value` | array | Value to add at the beginning of the list | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated number of items in the list. - -## Usage - -<<< ./snippets/lpushx-1.java - -> Callback response: - -```json -4 -``` diff --git a/doc/2/core-classes/memory-storage/lpushx/snippets/lpushx-1.java b/doc/2/core-classes/memory-storage/lpushx/snippets/lpushx-1.java deleted file mode 100644 index 6e5ef524..00000000 --- a/doc/2/core-classes/memory-storage/lpushx/snippets/lpushx-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.lpushx("key", "foo", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/lrange/index.md b/doc/2/core-classes/memory-storage/lrange/index.md deleted file mode 100644 index ac5ce2e8..00000000 --- a/doc/2/core-classes/memory-storage/lrange/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: lrange -description: MemoryStorage:lrange ---- - -# lrange - -Returns the list elements between the start and stop positions (inclusive). - -[[_Redis documentation_]](https://redis.io/commands/lrange) - ---- - -## lrange(key, start, stop, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `start` | int | Start position | -| `stop` | int | End position | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of retrieved values. - -## Usage - -<<< ./snippets/lrange-1.java - -> Callback response: - -```json -["foo", "bar"] -``` diff --git a/doc/2/core-classes/memory-storage/lrange/snippets/lrange-1.java b/doc/2/core-classes/memory-storage/lrange/snippets/lrange-1.java deleted file mode 100644 index 62ce39ce..00000000 --- a/doc/2/core-classes/memory-storage/lrange/snippets/lrange-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.lrange("key", 0, 1, new ResponseListener() { - @Override - public void onSuccess(String[] values) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/lrem/index.md b/doc/2/core-classes/memory-storage/lrem/index.md deleted file mode 100644 index 384a0010..00000000 --- a/doc/2/core-classes/memory-storage/lrem/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: lrem -description: MemoryStorage:lrem ---- - -# lrem - -Removes the first `count` occurences of elements equal to `value` from a list. - -[[_Redis documentation_]](https://redis.io/commands/lrem) - ---- - -## lrem(key, count, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------- | -| `key` | string | Key identifier | -| `count` | int | Number of occurences of the value to remove | -| `value` | string | Value to be removed from the list | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of removed elements. - -## Usage - -<<< ./snippets/lrem-1.java - -> Callback response: - -```json -1 -``` diff --git a/doc/2/core-classes/memory-storage/lrem/snippets/lrem-1.java b/doc/2/core-classes/memory-storage/lrem/snippets/lrem-1.java deleted file mode 100644 index 126c95af..00000000 --- a/doc/2/core-classes/memory-storage/lrem/snippets/lrem-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.lrem("key", 1, "foo", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/lset/index.md b/doc/2/core-classes/memory-storage/lset/index.md deleted file mode 100644 index 940a24b4..00000000 --- a/doc/2/core-classes/memory-storage/lset/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: lset -description: MemoryStorage:lset ---- - -# lset - -Sets the list element at `index` with the provided value. - -[[_Redis documentation_]](https://redis.io/commands/lset) - ---- - -## lset(key, index, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------ | -| `key` | string | Key identifier | -| `index` | int | Position of the list to update | -| `value` | string | New value at the provided list index | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/lset-1.java diff --git a/doc/2/core-classes/memory-storage/lset/snippets/lset-1.java b/doc/2/core-classes/memory-storage/lset/snippets/lset-1.java deleted file mode 100644 index 3c8020d0..00000000 --- a/doc/2/core-classes/memory-storage/lset/snippets/lset-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.lset("key", 2, "bar", new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/ltrim/index.md b/doc/2/core-classes/memory-storage/ltrim/index.md deleted file mode 100644 index 084161f3..00000000 --- a/doc/2/core-classes/memory-storage/ltrim/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: ltrim -description: MemoryStorage:ltrim ---- - -# ltrim - -Trims an existing list so that it will contain only the specified range of elements specified. - -[[_Redis documentation_]](https://redis.io/commands/ltrim) - ---- - -## ltrim(key, start, stop, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------------------- | -| `key` | string | Key identifier | -| `start` | int | Starting position of the range of items to keep (inclusive) | -| `stop` | int | Ending position of the range of items to keep (inclusive) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/ltrim-1.java diff --git a/doc/2/core-classes/memory-storage/ltrim/snippets/ltrim-1.java b/doc/2/core-classes/memory-storage/ltrim/snippets/ltrim-1.java deleted file mode 100644 index cbda48b4..00000000 --- a/doc/2/core-classes/memory-storage/ltrim/snippets/ltrim-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.ltrim("key", 1, 2, new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/mget/index.md b/doc/2/core-classes/memory-storage/mget/index.md deleted file mode 100644 index b7d97bf7..00000000 --- a/doc/2/core-classes/memory-storage/mget/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: mget -description: MemoryStorage:mget ---- - -# mget - -Returns the values of the provided keys. - -[[_Redis documentation_]](https://redis.io/commands/mget) - ---- - -## mget(keys, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------ | -| `keys` | string | List of keys to retrieve | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of the specified keys' values. - -## Usage - -<<< ./snippets/mget-1.java - -> Callback response: - -```json -["key1's value", "key2's value", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/mget/snippets/mget-1.java b/doc/2/core-classes/memory-storage/mget/snippets/mget-1.java deleted file mode 100644 index 497aafec..00000000 --- a/doc/2/core-classes/memory-storage/mget/snippets/mget-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.mget(keys, new ResponseListener() { - @Override - public void onSuccess(String[] values) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/mset/index.md b/doc/2/core-classes/memory-storage/mset/index.md deleted file mode 100644 index a002cb0c..00000000 --- a/doc/2/core-classes/memory-storage/mset/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: mset -description: MemoryStorage:mset ---- - -# mset - -Sets the provided keys to their respective values. If a key does not exist, it is created. Otherwise, the key’s value is overwritten. - -[[_Redis documentation_]](https://redis.io/commands/mset) - ---- - -## mset(entries, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `entries` | array | List of objects each containing the key identifier to add with its associated value.
Properties: `key` (key identifier), `value` (associated value) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/mset-1.java diff --git a/doc/2/core-classes/memory-storage/mset/snippets/mset-1.java b/doc/2/core-classes/memory-storage/mset/snippets/mset-1.java deleted file mode 100644 index c62533d2..00000000 --- a/doc/2/core-classes/memory-storage/mset/snippets/mset-1.java +++ /dev/null @@ -1,17 +0,0 @@ - -JSONObject[] entries = new JSONObject[]{ - new JSONObject().put("key", "key1").put("value", "foo"), - new JSONObject().put("key", "key2").put("value", "bar"), - new JSONObject().put("key", "...").put("value", "...") -}; - -kuzzle.memoryStorage.mset(entries, new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/msetnx/index.md b/doc/2/core-classes/memory-storage/msetnx/index.md deleted file mode 100644 index 5bcdda01..00000000 --- a/doc/2/core-classes/memory-storage/msetnx/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -code: true -type: page -title: msetnx -description: MemoryStorage:msetnx ---- - -# msetnx - -Sets the provided keys to their respective values, only if they do not exist. If a key exists, then the whole operation is aborted and no key is set. - -[[_Redis documentation_]](https://redis.io/commands/msetnx) - ---- - -## msetnx(entries, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `entries` | array | List of objects each containing the key identifier to add with its associated value.
Properties: `key` (key identifier), `value` (associated value) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/msetnx-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/msetnx/snippets/msetnx-1.java b/doc/2/core-classes/memory-storage/msetnx/snippets/msetnx-1.java deleted file mode 100644 index f86429ac..00000000 --- a/doc/2/core-classes/memory-storage/msetnx/snippets/msetnx-1.java +++ /dev/null @@ -1,17 +0,0 @@ - -JSONObject[] entries = new JSONObject[]{ - new JSONObject().put("key", "key1").put("value", "foo"), - new JSONObject().put("key", "key2").put("value", "bar"), - new JSONObject().put("key", "...").put("value", "...") -}; - -kuzzle.memoryStorage.msetnx(entries, new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/object/index.md b/doc/2/core-classes/memory-storage/object/index.md deleted file mode 100644 index 88887b11..00000000 --- a/doc/2/core-classes/memory-storage/object/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: object -description: MemoryStorage:object ---- - -# object - -Inspects the low-level properties of a key. - -[[_Redis documentation_]](https://redis.io/commands/object) - ---- - -## object(key, subcommand, [options], callback) - -| Arguments | Type | Description | -| ------------ | ----------- | ------------------------------------------------------------------------------------------------- | -| `key` | string | Key identifier | -| `subcommand` | string | Name of the low-level property to inspect.
Allowed values: `refcount`, `encoding`, `idletime` | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the value of the inspected property. - -## Usage - -<<< ./snippets/object-1.java - -> Callback response: - -```json -"raw" -``` diff --git a/doc/2/core-classes/memory-storage/object/snippets/object-1.java b/doc/2/core-classes/memory-storage/object/snippets/object-1.java deleted file mode 100644 index ac0bf4eb..00000000 --- a/doc/2/core-classes/memory-storage/object/snippets/object-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.object("key", "encoding", new ResponseListener() { - @Override - public void onSuccess(String property) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/persist/index.md b/doc/2/core-classes/memory-storage/persist/index.md deleted file mode 100644 index f1a808b2..00000000 --- a/doc/2/core-classes/memory-storage/persist/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: persist -description: MemoryStorage:persist ---- - -# persist - -Removes the expiration delay or timestamp from a key, making it persistent. - -[[_Redis documentation_]](https://redis.io/commands/persist) - ---- - -## persist(key, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/persist-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/persist/snippets/persist-1.java b/doc/2/core-classes/memory-storage/persist/snippets/persist-1.java deleted file mode 100644 index cee6b5b9..00000000 --- a/doc/2/core-classes/memory-storage/persist/snippets/persist-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.persist("key", new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/pexpire/index.md b/doc/2/core-classes/memory-storage/pexpire/index.md deleted file mode 100644 index 6f9e55af..00000000 --- a/doc/2/core-classes/memory-storage/pexpire/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: pexpire -description: MemoryStorage:pexpire ---- - -# pexpire - -Sets a timeout (in milliseconds) on a key. After the timeout has expired, the key will automatically be deleted. - -[[_Redis documentation_]](https://redis.io/commands/pexpire) - ---- - -## pexpire(key, ttl, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------------- | -| `key` | string | Key identifier | -| `ttl` | int | Time to live of the key, in milliseconds | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/pexpire-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/pexpire/snippets/pexpire-1.java b/doc/2/core-classes/memory-storage/pexpire/snippets/pexpire-1.java deleted file mode 100644 index b66ebe6d..00000000 --- a/doc/2/core-classes/memory-storage/pexpire/snippets/pexpire-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.pexpire("key", 42000, new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/pexpireat/index.md b/doc/2/core-classes/memory-storage/pexpireat/index.md deleted file mode 100644 index bcd138b8..00000000 --- a/doc/2/core-classes/memory-storage/pexpireat/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: pexpireat -description: MemoryStorage:pexpireat ---- - -# pexpireat - -Sets an expiration timestamp on a key. After the timestamp has been reached, the key will automatically be deleted. -The `timestamp` parameter accepts an [Epoch time](https://en.wikipedia.org/wiki/Unix_time) value, in milliseconds. - -[[_Redis documentation_]](https://redis.io/commands/pexpireat) - ---- - -## pexpireat(key, timestamp, [options], [callback]) - -| Arguments | Type | Description | -| ----------- | ----------- | ------------------------------------------- | -| `key` | string | Key identifier | -| `timestamp` | int | Key's expiration timestamp, in milliseconds | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/pexpireat-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/pexpireat/snippets/pexpireat-1.java b/doc/2/core-classes/memory-storage/pexpireat/snippets/pexpireat-1.java deleted file mode 100644 index 960ede21..00000000 --- a/doc/2/core-classes/memory-storage/pexpireat/snippets/pexpireat-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.pexpireat("key", 1488540242465, new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/pfadd/index.md b/doc/2/core-classes/memory-storage/pfadd/index.md deleted file mode 100644 index 0e0b48fc..00000000 --- a/doc/2/core-classes/memory-storage/pfadd/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: pfadd -description: MemoryStorage:pfadd ---- - -# pfadd - -Adds elements to an [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) data structure. - -[[_Redis documentation_]](https://redis.io/commands/pfadd) - ---- - -## pfadd(key, elements, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------- | -| `key` | string | Key identifier | -| `elements` | array | Elements to add to the HyperLogLog structure | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/pfadd-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/pfadd/snippets/pfadd-1.java b/doc/2/core-classes/memory-storage/pfadd/snippets/pfadd-1.java deleted file mode 100644 index ee922fad..00000000 --- a/doc/2/core-classes/memory-storage/pfadd/snippets/pfadd-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] elements = new String[]{"foo", "bar", "baz"}; - -kuzzle.memoryStorage.pfadd("key", elements, new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/pfcount/index.md b/doc/2/core-classes/memory-storage/pfcount/index.md deleted file mode 100644 index 5753bbae..00000000 --- a/doc/2/core-classes/memory-storage/pfcount/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: pfcount -description: MemoryStorage:pfcount ---- - -# pfcount - -Returns the probabilistic cardinality of a [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) data structure, or of the merged HyperLogLog structures if more than 1 is provided (see [pfadd](/sdk/java/2/core-classes/memory-storage/pfadd)). - -[[_Redis documentation_]](https://redis.io/commands/pfcount) - ---- - -## pfcount(keys, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------- | -| `keys` | string | List of HyperLogLog key identifiers | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the aggregated probabilistic cardinality of HyperLogLog structures. - -## Usage - -<<< ./snippets/pfcount-1.java - -> Callback response: - -```json -42 -``` diff --git a/doc/2/core-classes/memory-storage/pfcount/snippets/pfcount-1.java b/doc/2/core-classes/memory-storage/pfcount/snippets/pfcount-1.java deleted file mode 100644 index bd76126b..00000000 --- a/doc/2/core-classes/memory-storage/pfcount/snippets/pfcount-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.pfcount(keys, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/pfmerge/index.md b/doc/2/core-classes/memory-storage/pfmerge/index.md deleted file mode 100644 index ca30bf81..00000000 --- a/doc/2/core-classes/memory-storage/pfmerge/index.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -code: true -type: page -title: pfmerge -description: MemoryStorage:pfmerge ---- - -# pfmerge - -Merges multiple [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) data structures into an unique HyperLogLog structure stored at `key`, approximating the cardinality of the union of the source structures. - -[[_Redis documentation_]](https://redis.io/commands/pfmerge) - ---- - -## pfmerge(key, sources, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------ | -| `key` | string | Destination key identifier | -| `sources` | string | List of HyperLogLog source key identifiers | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/pfmerge-1.java diff --git a/doc/2/core-classes/memory-storage/pfmerge/snippets/pfmerge-1.java b/doc/2/core-classes/memory-storage/pfmerge/snippets/pfmerge-1.java deleted file mode 100644 index 55b1539a..00000000 --- a/doc/2/core-classes/memory-storage/pfmerge/snippets/pfmerge-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.pfmerge('key', keys, new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/ping/index.md b/doc/2/core-classes/memory-storage/ping/index.md deleted file mode 100644 index 735a0c50..00000000 --- a/doc/2/core-classes/memory-storage/ping/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -code: true -type: page -title: ping -description: MemoryStorage:ping ---- - -# ping - -Pings the memory storage database. - -[[_Redis documentation_]](https://redis.io/commands/ping) - ---- - -## ping([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a simple "PONG" string. - -## Usage - -<<< ./snippets/ping-1.java - -> Callback response: - -```json -"PONG" -``` diff --git a/doc/2/core-classes/memory-storage/ping/snippets/ping-1.java b/doc/2/core-classes/memory-storage/ping/snippets/ping-1.java deleted file mode 100644 index 20ccdfa4..00000000 --- a/doc/2/core-classes/memory-storage/ping/snippets/ping-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.ping(new ResponseListener() { - @Override - public void onSuccess(String response) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/psetex/index.md b/doc/2/core-classes/memory-storage/psetex/index.md deleted file mode 100644 index ce04eb02..00000000 --- a/doc/2/core-classes/memory-storage/psetex/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: psetex -description: MemoryStorage:psetex ---- - -# psetex - -Sets a key with the provided value, and an expiration delay expressed in milliseconds. If the key does not exist, it is created beforehand. - -[[_Redis documentation_]](https://redis.io/commands/psetex) - ---- - -## psetex(key, value, ttl, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------------- | -| `key` | string | Key identifier | -| `value` | string | Value to set | -| `ttl` | int | Time to live of the key, in milliseconds | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/psetex-1.java diff --git a/doc/2/core-classes/memory-storage/psetex/snippets/psetex-1.java b/doc/2/core-classes/memory-storage/psetex/snippets/psetex-1.java deleted file mode 100644 index 34a2098c..00000000 --- a/doc/2/core-classes/memory-storage/psetex/snippets/psetex-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.psetex("key", "value", 42000, new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/pttl/index.md b/doc/2/core-classes/memory-storage/pttl/index.md deleted file mode 100644 index b7436955..00000000 --- a/doc/2/core-classes/memory-storage/pttl/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: pttl -description: MemoryStorage:pttl ---- - -# pttl - -Returns the remaining time to live of a key, in milliseconds. - -[[_Redis documentation_]](https://redis.io/commands/pttl) - ---- - -## pttl(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the remaining time to live of the key, in milliseconds. - -## Usage - -<<< ./snippets/pttl-1.java - -> Callback response: - -```json -43159 -``` diff --git a/doc/2/core-classes/memory-storage/pttl/snippets/pttl-1.java b/doc/2/core-classes/memory-storage/pttl/snippets/pttl-1.java deleted file mode 100644 index e20fd472..00000000 --- a/doc/2/core-classes/memory-storage/pttl/snippets/pttl-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.pttl("key", new ResponseListener() { - @Override - public void onSuccess(int ttl) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/randomkey/index.md b/doc/2/core-classes/memory-storage/randomkey/index.md deleted file mode 100644 index cf025845..00000000 --- a/doc/2/core-classes/memory-storage/randomkey/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -code: true -type: page -title: randomkey -description: MemoryStorage:randomkey ---- - -# randomkey - -Returns a random key from the memory storage. - -[[_Redis documentation_]](https://redis.io/commands/randomkey) - ---- - -## randomkey([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns one of the stored key names, at random. - -## Usage - -<<< ./snippets/randomkey-1.java - -> Callback response: - -```json -"key2" -``` diff --git a/doc/2/core-classes/memory-storage/randomkey/snippets/randomkey-1.java b/doc/2/core-classes/memory-storage/randomkey/snippets/randomkey-1.java deleted file mode 100644 index 5fbe9692..00000000 --- a/doc/2/core-classes/memory-storage/randomkey/snippets/randomkey-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.randomkey(new ResponseListener() { - @Override - public void onSuccess(String key) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/rename/index.md b/doc/2/core-classes/memory-storage/rename/index.md deleted file mode 100644 index afe8664f..00000000 --- a/doc/2/core-classes/memory-storage/rename/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: rename -description: MemoryStorage:rename ---- - -# rename - -Renames a key to `newkey`. If `newkey` already exists, it is overwritten. - -[[_Redis documentation_]](https://redis.io/commands/rename) - ---- - -## rename(key, newkey, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `newkey` | string | New key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/rename-1.java diff --git a/doc/2/core-classes/memory-storage/rename/snippets/rename-1.java b/doc/2/core-classes/memory-storage/rename/snippets/rename-1.java deleted file mode 100644 index dc5e7896..00000000 --- a/doc/2/core-classes/memory-storage/rename/snippets/rename-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.rename("key", "newId", new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/renamenx/index.md b/doc/2/core-classes/memory-storage/renamenx/index.md deleted file mode 100644 index b6879e84..00000000 --- a/doc/2/core-classes/memory-storage/renamenx/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: renamenx -description: MemoryStorage:renamenx ---- - -# renamenx - -Renames a key to `newkey`, only if `newkey` does not already exist. - -[[_Redis documentation_]](https://redis.io/commands/renamenx) - ---- - -## renamenx(key, newkey, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `newkey` | string | New key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/renamenx-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/renamenx/snippets/renamenx-1.java b/doc/2/core-classes/memory-storage/renamenx/snippets/renamenx-1.java deleted file mode 100644 index 4da35cd2..00000000 --- a/doc/2/core-classes/memory-storage/renamenx/snippets/renamenx-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.renamenx("key", "newId", new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/rpop/index.md b/doc/2/core-classes/memory-storage/rpop/index.md deleted file mode 100644 index 661678ef..00000000 --- a/doc/2/core-classes/memory-storage/rpop/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: rpop -description: MemoryStorage:rpop ---- - -# rpop - -Removes and returns the last element of a list. - -[[_Redis documentation_]](https://redis.io/commands/rpop) - ---- - -## rpop(key, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns the value of the removed item. - -## Usage - -<<< ./snippets/rpop-1.java - -> Callback response: - -```json -"foo" -``` diff --git a/doc/2/core-classes/memory-storage/rpop/snippets/rpop-1.java b/doc/2/core-classes/memory-storage/rpop/snippets/rpop-1.java deleted file mode 100644 index c36e5f63..00000000 --- a/doc/2/core-classes/memory-storage/rpop/snippets/rpop-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.rpop("key", new ResponseListener() { - @Override - public void onSuccess(String value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/rpoplpush/index.md b/doc/2/core-classes/memory-storage/rpoplpush/index.md deleted file mode 100644 index 5177ec5b..00000000 --- a/doc/2/core-classes/memory-storage/rpoplpush/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: rpoplpush -description: MemoryStorage:rpoplpush ---- - -# rpoplpush - -Removes the last element of the list at `source` and pushes it back at the start of the list at `destination`. - -[[_Redis documentation_]](https://redis.io/commands/rpoplpush) - ---- - -## rpoplpush(source, destination, [options], [callback]) - -| Arguments | Type | Description | -| ------------- | ----------- | -------------------------- | -| `source` | string | Source key identifier | -| `destination` | string | Destination key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns the value of the removed and pushed item. - -## Usage - -<<< ./snippets/rpoplpush-1.java - -> Callback response: - -```json -"foo" -``` diff --git a/doc/2/core-classes/memory-storage/rpoplpush/snippets/rpoplpush-1.java b/doc/2/core-classes/memory-storage/rpoplpush/snippets/rpoplpush-1.java deleted file mode 100644 index f1f49aa7..00000000 --- a/doc/2/core-classes/memory-storage/rpoplpush/snippets/rpoplpush-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.rpoplpush("sourceKey", "destKey", new ResponseListener() { - @Override - public void onSuccess(String value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/rpush/index.md b/doc/2/core-classes/memory-storage/rpush/index.md deleted file mode 100644 index 1cf04d5a..00000000 --- a/doc/2/core-classes/memory-storage/rpush/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: rpush -description: MemoryStorage:rpush ---- - -# rpush - -Appends the specified values at the end of a list. If the key does not exist, it is created holding an empty list before performing the operation. - -[[_Redis documentation_]](https://redis.io/commands/rpush) - ---- - -## rpush(key, values, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------ | -| `key` | string | Key identifier | -| `values` | array | Values to add at the end of the list | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated number of items in the list. - -## Usage - -<<< ./snippets/rpush-1.java - -> Callback response: - -```json -6 -``` diff --git a/doc/2/core-classes/memory-storage/rpush/snippets/rpush-1.java b/doc/2/core-classes/memory-storage/rpush/snippets/rpush-1.java deleted file mode 100644 index a5a53aac..00000000 --- a/doc/2/core-classes/memory-storage/rpush/snippets/rpush-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] items = new String[]{"foo", "bar", "baz"}; - -kuzzle.memoryStorage.rpush("key", items, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/rpushx/index.md b/doc/2/core-classes/memory-storage/rpushx/index.md deleted file mode 100644 index 34fb353e..00000000 --- a/doc/2/core-classes/memory-storage/rpushx/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: rpushx -description: MemoryStorage:rpushx ---- - -# rpushx - -Appends the specified value at the end of a list, only if the key already exists and if it holds a list. - -[[_Redis documentation_]](https://redis.io/commands/rpushx) - ---- - -## rpushx(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------- | -| `key` | string | Key identifier | -| `value` | string | Value to add at the end of the list | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the updated number of items in the list. - -## Usage - -<<< ./snippets/rpushx-1.java - -> Callback response: - -```json -4 -``` diff --git a/doc/2/core-classes/memory-storage/rpushx/snippets/rpushx-1.java b/doc/2/core-classes/memory-storage/rpushx/snippets/rpushx-1.java deleted file mode 100644 index 50f20def..00000000 --- a/doc/2/core-classes/memory-storage/rpushx/snippets/rpushx-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.rpushx("key", "foo", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sadd/index.md b/doc/2/core-classes/memory-storage/sadd/index.md deleted file mode 100644 index 0f6dfadd..00000000 --- a/doc/2/core-classes/memory-storage/sadd/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: sadd -description: MemoryStorage:sadd ---- - -# sadd - -Adds members to a set of unique values stored at `key`. If the `key` does not exist, it is created beforehand. - -[[_Redis documentation_]](https://redis.io/commands/sadd) - ---- - -## sadd(key, members, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------- | -| `key` | string | Key identifier | -| `members` | array | Members to add to the list of unique values | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of added elements to the set. - -## Usage - -<<< ./snippets/sadd-1.java - -> Callback response: - -```json -6 -``` diff --git a/doc/2/core-classes/memory-storage/sadd/snippets/sadd-1.java b/doc/2/core-classes/memory-storage/sadd/snippets/sadd-1.java deleted file mode 100644 index fc24e362..00000000 --- a/doc/2/core-classes/memory-storage/sadd/snippets/sadd-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] items = new String[]{"foo", "bar", "baz"}; - -kuzzle.memoryStorage.sadd("key", items, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/scan/index.md b/doc/2/core-classes/memory-storage/scan/index.md deleted file mode 100644 index a797cd76..00000000 --- a/doc/2/core-classes/memory-storage/scan/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -code: true -type: page -title: scan -description: MemoryStorage:scan ---- - -# scan - -Iterates incrementally over the set of keys in the database using a cursor. - -An iteration starts when the cursor is set to `0`. -To get the next page of results, simply re-send the identical request with the updated cursor position provided in the result set. -The scan terminates when the next position cursor returned by the server is `0`. - -[[_Redis documentation_]](https://redis.io/commands/scan) - ---- - -## scan(cursor, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------- | -| `cursor` | int | Page number (iteration starts with a cursor value of `0`, and ends when the next cursor position is `0`) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------------------------------------- | ------- | -| `count` | int | Return the _approximate_ `count` number of items per result page | `10` | -| `match` | string | Search only for field names matching the provided pattern | `*` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a JSON object containing 2 entries: - -- the cursor position for the next page of results (a next position of `0` indicates the end of the scan) -- a list of fetched keys - -## Usage - -<<< ./snippets/scan-1.java - -> Callback response: - -```json -{ - "cursor": 18, - "values": ["key1", "key2", "..."] -} -``` diff --git a/doc/2/core-classes/memory-storage/scan/snippets/scan-1.java b/doc/2/core-classes/memory-storage/scan/snippets/scan-1.java deleted file mode 100644 index d9665783..00000000 --- a/doc/2/core-classes/memory-storage/scan/snippets/scan-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.scan(0, new ResponseListener() { - @Override - public void onSuccess(JSONObject page) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/scard/index.md b/doc/2/core-classes/memory-storage/scard/index.md deleted file mode 100644 index c41f7f70..00000000 --- a/doc/2/core-classes/memory-storage/scard/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: scard -description: MemoryStorage:scard ---- - -# scard - -Returns the number of members stored in a set of unique values. - -[[_Redis documentation_]](https://redis.io/commands/scard) - ---- - -## scard(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of items in the set. - -## Usage - -<<< ./snippets/scard-1.java - -> Callback response: - -```json -3 -``` diff --git a/doc/2/core-classes/memory-storage/scard/snippets/scard-1.java b/doc/2/core-classes/memory-storage/scard/snippets/scard-1.java deleted file mode 100644 index 4b4e0e48..00000000 --- a/doc/2/core-classes/memory-storage/scard/snippets/scard-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.scard("key", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sdiff/index.md b/doc/2/core-classes/memory-storage/sdiff/index.md deleted file mode 100644 index b145e8a8..00000000 --- a/doc/2/core-classes/memory-storage/sdiff/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: sdiff -description: MemoryStorage:sdiff ---- - -# sdiff - -Returns the difference between the set of unique values stored at `key` and the other provided sets. - -[[_Redis documentation_]](https://redis.io/commands/sdiff) - ---- - -## sdiff(key, keys, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------- | -| `key` | string | Key identifier to compare | -| `keys` | array | list of set keys to compare with the set stored at `key` | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of differences. - -## Usage - -<<< ./snippets/sdiff-1.java - -> Callback response: - -```json -["diff value1", "diff value2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/sdiff/snippets/sdiff-1.java b/doc/2/core-classes/memory-storage/sdiff/snippets/sdiff-1.java deleted file mode 100644 index c6ee97c9..00000000 --- a/doc/2/core-classes/memory-storage/sdiff/snippets/sdiff-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.sdiff("key", keys, new ResponseListener() { - @Override - public void onSuccess(String[] diffs) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sdiffstore/index.md b/doc/2/core-classes/memory-storage/sdiffstore/index.md deleted file mode 100644 index c5a399d5..00000000 --- a/doc/2/core-classes/memory-storage/sdiffstore/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -code: true -type: page -title: sdiffstore -description: MemoryStorage:sdiffstore ---- - -# sdiffstore - -Computes the difference between the set of unique values stored at `key` and the other provided sets, and stores the result in the key stored at `destination`. - -If the `destination` key already exists, it is overwritten. - -[[_Redis documentation_]](https://redis.io/commands/sdiffstore) - ---- - -## sdiffstore(key, keys, destination, [options], [callback]) - -| Arguments | Type | Description | -| ------------- | ----------- | -------------------------------------------------------- | -| `key` | string | Key identifier to compare | -| `keys` | array | list of set keys to compare with the set stored at `key` | -| `destination` | string | Destination key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of stored elements. - -## Usage - -<<< ./snippets/sdiffstore-1.java - -> Callback response: - -```json -3 -``` diff --git a/doc/2/core-classes/memory-storage/sdiffstore/snippets/sdiffstore-1.java b/doc/2/core-classes/memory-storage/sdiffstore/snippets/sdiffstore-1.java deleted file mode 100644 index f18b297b..00000000 --- a/doc/2/core-classes/memory-storage/sdiffstore/snippets/sdiffstore-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.sdiffstore("key", keys, "destination", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/set/index.md b/doc/2/core-classes/memory-storage/set/index.md deleted file mode 100644 index 1e6b5d59..00000000 --- a/doc/2/core-classes/memory-storage/set/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -code: true -type: page -title: set -description: MemoryStorage:set ---- - -# set - -Creates a key holding the provided value, or overwrites it if it already exists. - -[[_Redis documentation_]](https://redis.io/commands/set) - ---- - -## set(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `value` | string | Value to store | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------------------- | ------- | -| `ex` | int | Time to live of the key, in seconds | `0` | -| `nx` | boolean | Set the key only if it does not already exist | `false` | -| `px` | int | Time to live of the key, in milliseconds | `0` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `xx` | boolean | Set the key only if it already exists | `false` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/set-1.java diff --git a/doc/2/core-classes/memory-storage/set/snippets/set-1.java b/doc/2/core-classes/memory-storage/set/snippets/set-1.java deleted file mode 100644 index 7635c8ea..00000000 --- a/doc/2/core-classes/memory-storage/set/snippets/set-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.set("key", "value", new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/setex/index.md b/doc/2/core-classes/memory-storage/setex/index.md deleted file mode 100644 index 219a6534..00000000 --- a/doc/2/core-classes/memory-storage/setex/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: setex -description: MemoryStorage:setex ---- - -# setex - -Sets a key with the provided value, and an expiration delay expressed in seconds. If the key does not exist, it is created beforehand. - -[[_Redis documentation_]](https://redis.io/commands/setex) - ---- - -## setex(key, value, ttl, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------- | -| `key` | string | Key identifier | -| `value` | string | Value to set | -| `ttl` | int | Time to live of the key, in seconds | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns null if successful. - -## Usage - -<<< ./snippets/setex-1.java diff --git a/doc/2/core-classes/memory-storage/setex/snippets/setex-1.java b/doc/2/core-classes/memory-storage/setex/snippets/setex-1.java deleted file mode 100644 index 33415acf..00000000 --- a/doc/2/core-classes/memory-storage/setex/snippets/setex-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.setex("key", "value", 42, new ResponseListener() { - @Override - public void onSuccess(Void v) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/setnx/index.md b/doc/2/core-classes/memory-storage/setnx/index.md deleted file mode 100644 index cdfbaaad..00000000 --- a/doc/2/core-classes/memory-storage/setnx/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: setnx -description: MemoryStorage:setnx ---- - -# setnx - -Sets a value on a key, only if it does not already exist. - -[[_Redis documentation_]](https://redis.io/commands/setnx) - ---- - -## setnx(key, value, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `value` | string | Value to store | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/setnx-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/setnx/snippets/setnx-1.java b/doc/2/core-classes/memory-storage/setnx/snippets/setnx-1.java deleted file mode 100644 index 9de04ac1..00000000 --- a/doc/2/core-classes/memory-storage/setnx/snippets/setnx-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.setnx("key", "value", new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sinter/index.md b/doc/2/core-classes/memory-storage/sinter/index.md deleted file mode 100644 index 121ebbff..00000000 --- a/doc/2/core-classes/memory-storage/sinter/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: sinter -description: MemoryStorage:sinter ---- - -# sinter - -Returns the intersection of the provided sets of unique values. - -[[_Redis documentation_]](https://redis.io/commands/sinter) - ---- - -## sinter(keys, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------ | -| `keys` | string | List of sets of unique values to intersect | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of values in the computed intersection. - -## Usage - -<<< ./snippets/sinter-1.java - -> Callback response: - -```json -["intersection value1", "intersection value2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/sinter/snippets/sinter-1.java b/doc/2/core-classes/memory-storage/sinter/snippets/sinter-1.java deleted file mode 100644 index bc7fa696..00000000 --- a/doc/2/core-classes/memory-storage/sinter/snippets/sinter-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.sinter(keys, new ResponseListener() { - @Override - public void onSuccess(String[] values) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sinterstore/index.md b/doc/2/core-classes/memory-storage/sinterstore/index.md deleted file mode 100644 index 36086043..00000000 --- a/doc/2/core-classes/memory-storage/sinterstore/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: sinterstore -description: MemoryStorage:sinterstore ---- - -# sinterstore - -Computes the intersection of the provided sets of unique values and stores the result in the `destination` key. - -If the destination key already exists, it is overwritten. - -[[_Redis documentation_]](https://redis.io/commands/sinterstore) - ---- - -## sinterstore(destination, keys, [options], callback) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------ | -| `destination` | string | Destination key identifier | -| `keys` | array | List of sets of unique values to intersect | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of elements in the stored intersection. - -## Usage - -<<< ./snippets/sinterstore-1.java - -> Callback response: - -```json -4 -``` diff --git a/doc/2/core-classes/memory-storage/sinterstore/snippets/sinterstore-1.java b/doc/2/core-classes/memory-storage/sinterstore/snippets/sinterstore-1.java deleted file mode 100644 index 4c1b9b7e..00000000 --- a/doc/2/core-classes/memory-storage/sinterstore/snippets/sinterstore-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.sinterstore("destination", keys, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sismember/index.md b/doc/2/core-classes/memory-storage/sismember/index.md deleted file mode 100644 index 424f6513..00000000 --- a/doc/2/core-classes/memory-storage/sismember/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: sismember -description: MemoryStorage:sismember ---- - -# sismember - -Checks if `member` is a member of the set of unique values stored at `key`. - -[[_Redis documentation_]](https://redis.io/commands/sismember) - ---- - -## sismember(key, member, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------------- | -| `key` | string | Key identifier | -| `member` | string | Value tested against the set of unique values | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a boolean specifying if `member` is a member of the set or not. - -## Usage - -<<< ./snippets/sismember-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/sismember/snippets/sismember-1.java b/doc/2/core-classes/memory-storage/sismember/snippets/sismember-1.java deleted file mode 100644 index 97297bc8..00000000 --- a/doc/2/core-classes/memory-storage/sismember/snippets/sismember-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.sismember("key", "member", new ResponseListener() { - @Override - public void onSuccess(Boolean isMember) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/smembers/index.md b/doc/2/core-classes/memory-storage/smembers/index.md deleted file mode 100644 index fce322ea..00000000 --- a/doc/2/core-classes/memory-storage/smembers/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -code: true -type: page -title: smembers -description: MemoryStorage:smembers ---- - -# smembers - -Returns the members of a set of unique values. - -[[_Redis documentation_]](https://redis.io/commands/smembers) - ---- - -## smembers(key, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of values held by the provided set. - -## Usage - -<<< ./snippets/smembers-1.java - -> Callback response: - -```json -["member1", "member2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/smembers/snippets/smembers-1.java b/doc/2/core-classes/memory-storage/smembers/snippets/smembers-1.java deleted file mode 100644 index 4a15f88f..00000000 --- a/doc/2/core-classes/memory-storage/smembers/snippets/smembers-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.smembers("key", new ResponseListener() { - @Override - public void onSuccess(String[] members) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/smove/index.md b/doc/2/core-classes/memory-storage/smove/index.md deleted file mode 100644 index dad1c1f6..00000000 --- a/doc/2/core-classes/memory-storage/smove/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: smove -description: MemoryStorage:smove ---- - -# smove - -Moves a member from a set of unique values to another. - -[[_Redis documentation_]](https://redis.io/commands/smove) - ---- - -## smove(key, destination, member, [options], [callback]) - -| Arguments | Type | Description | -| ------------- | ----------- | -------------------------- | -| `key` | string | Source key identifier | -| `destination` | string | Destination key identifier | -| `member` | string | Member to be moved | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a boolean specifying if the operation was successful or not. - -## Usage - -<<< ./snippets/smove-1.java - -> Callback response: - -```json -true -``` diff --git a/doc/2/core-classes/memory-storage/smove/snippets/smove-1.java b/doc/2/core-classes/memory-storage/smove/snippets/smove-1.java deleted file mode 100644 index b6843e40..00000000 --- a/doc/2/core-classes/memory-storage/smove/snippets/smove-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.smove("key", "destination", "member", new ResponseListener() { - @Override - public void onSuccess(Boolean status) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sort/index.md b/doc/2/core-classes/memory-storage/sort/index.md deleted file mode 100644 index 9b85788c..00000000 --- a/doc/2/core-classes/memory-storage/sort/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -code: true -type: page -title: sort -description: MemoryStorage:sort ---- - -# sort - -Sorts and returns elements contained in a list, a set of unique values or a sorted set. -By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. - -:::info -While Kuzzle's API supports the "store" option for this command, Kuzzle SDK methods do not. To sort and store in the same process, use the [query method](/sdk/java/2/core-classes/kuzzle/query) -::: - -[[_Redis documentation_]](https://redis.io/commands/sort) - -### sort(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `alpha` | boolean | Perform an alphanumerical sort instead of a numeric one | `false` | -| `by` | string | Instead of sorting the values stored at `key`, use them to complete the provided key pattern, and return the sorted list of values stored in those keys. | `null` | -| `direction` | string | Sort in ascendant (`ASC`) or descendant (`DESC`) order | `ASC` | -| `get` | array | Sort the values stored at `key` but, instead of returning these directly, return the values contained in external keys, using the provided array of patterns completed by the sorted values | `null` | -| `limit` | array | Limit the result set to a range of matching elements (similar to _SELECT LIMIT offset, count_ in SQL).
Format: `[, ]` | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | - -### Callback Response - -Returns an array of sorted values. - -## Usage - -<<< ./snippets/sort-1.java - -> Callback response: - -```json -["sorted element1", "sorted element2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/sort/snippets/sort-1.java b/doc/2/core-classes/memory-storage/sort/snippets/sort-1.java deleted file mode 100644 index aa250a94..00000000 --- a/doc/2/core-classes/memory-storage/sort/snippets/sort-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.sort("key", new ResponseListener() { - @Override - public void onSuccess(String[] values) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/spop/index.md b/doc/2/core-classes/memory-storage/spop/index.md deleted file mode 100644 index 81a204ac..00000000 --- a/doc/2/core-classes/memory-storage/spop/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: spop -description: MemoryStorage:spop ---- - -# spop - -Removes and returns one or more elements at random from a set of unique values. - -[[_Redis documentation_]](https://redis.io/commands/spop) - ---- - -## spop(key, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `count` | int | Number of elements to remove | `1` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of removed elements. - -## Usage - -<<< ./snippets/spop-1.java - -> Callback response: - -```json -["removed element"] -``` diff --git a/doc/2/core-classes/memory-storage/spop/snippets/spop-1.java b/doc/2/core-classes/memory-storage/spop/snippets/spop-1.java deleted file mode 100644 index db7a18b7..00000000 --- a/doc/2/core-classes/memory-storage/spop/snippets/spop-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.spop("key", new ResponseListener() { - @Override - public void onSuccess(String[] elements) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/srandmember/index.md b/doc/2/core-classes/memory-storage/srandmember/index.md deleted file mode 100644 index 1ead4ac9..00000000 --- a/doc/2/core-classes/memory-storage/srandmember/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: srandmember -description: MemoryStorage:srandmember ---- - -# srandmember - -Returns one or more members of a set of unique values, at random. -If `count` is provided and is positive, the returned values are unique. If `count` is negative, a set member can be returned multiple times. - -[[_Redis documentation_]](https://redis.io/commands/srandmember) - ---- - -## srandmember(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `count` | int | Number of members to return. If set with a positive value, the returned values are unique. If `count` is negative, a set member can be returned multiple times | `1` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of members of a set of unique values. - -## Usage - -<<< ./snippets/srandmember-1.java - -> Callback response: - -```json -["member1", "member2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/srandmember/snippets/srandmember-1.java b/doc/2/core-classes/memory-storage/srandmember/snippets/srandmember-1.java deleted file mode 100644 index fa4ffc3d..00000000 --- a/doc/2/core-classes/memory-storage/srandmember/snippets/srandmember-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.srandmember("key", new ResponseListener() { - @Override - public void onSuccess(String[] members) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/srem/index.md b/doc/2/core-classes/memory-storage/srem/index.md deleted file mode 100644 index bdeb17a3..00000000 --- a/doc/2/core-classes/memory-storage/srem/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: srem -description: MemoryStorage:srem ---- - -# srem - -Removes members from a set of unique values. - -[[_Redis documentation_]](https://redis.io/commands/srem) - ---- - -## srem(key, members, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------- | -| `key` | string | Key identifier | -| `members` | array | List of members to remove from the set | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of removed elements. - -## Usage - -<<< ./snippets/srem-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/srem/snippets/srem-1.java b/doc/2/core-classes/memory-storage/srem/snippets/srem-1.java deleted file mode 100644 index f6b312b7..00000000 --- a/doc/2/core-classes/memory-storage/srem/snippets/srem-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] members = new String[]{"member1", "member2", "..."}; - -kuzzle.memoryStorage.srem("key", members, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sscan/index.md b/doc/2/core-classes/memory-storage/sscan/index.md deleted file mode 100644 index dc51561a..00000000 --- a/doc/2/core-classes/memory-storage/sscan/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: sscan -description: MemoryStorage:sscan ---- - -# sscan - -Identical to [scan](/sdk/java/2/core-classes/memory-storage/scan), except that `sscan` iterates the members held by a set of unique values. - -[[_Redis documentation_]](https://redis.io/commands/sscan) - ---- - -## sscan(key, cursor, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------- | -| `key` | string | Key identifier | -| `cursor` | int | Page number (iteration starts with a cursor value of `0`, and ends when the next cursor position is `0`) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------------------------------------- | ------- | -| `count` | int | Return the _approximate_ `count` number of items per result page | `10` | -| `match` | string | Search only for member values matching the provided pattern | `*` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a JSON array containing 2 entries: - -- the cursor position for the next page of results (a next position of `0` indicates the end of the scan) -- an array of members - -## Usage - -<<< ./snippets/sscan-1.java - -> Callback response: - -```json -{ - "cursor": 18, - "values": ["member1", "member2", "..."] -} -``` diff --git a/doc/2/core-classes/memory-storage/sscan/snippets/sscan-1.java b/doc/2/core-classes/memory-storage/sscan/snippets/sscan-1.java deleted file mode 100644 index 37160c59..00000000 --- a/doc/2/core-classes/memory-storage/sscan/snippets/sscan-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.sscan("key", 0, new ResponseListener() { - @Override - public void onSuccess(JSONObject page) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/strlen/index.md b/doc/2/core-classes/memory-storage/strlen/index.md deleted file mode 100644 index ebdf7ca1..00000000 --- a/doc/2/core-classes/memory-storage/strlen/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: strlen -description: MemoryStorage:strlen ---- - -# strlen - -Returns the length of a value stored at `key`. - -[[_Redis documentation_]](https://redis.io/commands/strlen) - ---- - -## strlen(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the length of a value. - -## Usage - -<<< ./snippets/strlen-1.java - -> Callback response: - -```json -13 -``` diff --git a/doc/2/core-classes/memory-storage/strlen/snippets/strlen-1.java b/doc/2/core-classes/memory-storage/strlen/snippets/strlen-1.java deleted file mode 100644 index 89461479..00000000 --- a/doc/2/core-classes/memory-storage/strlen/snippets/strlen-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.strlen("key", new ResponseListener() { - @Override - public void onSuccess(int length) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sunion/index.md b/doc/2/core-classes/memory-storage/sunion/index.md deleted file mode 100644 index 198e1964..00000000 --- a/doc/2/core-classes/memory-storage/sunion/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: sunion -description: MemoryStorage:sunion ---- - -# sunion - -Returns the union of the provided sets of unique values. - -[[_Redis documentation_]](https://redis.io/commands/sunion) - ---- - -## sunion(keys, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------- | -| `keys` | string | List of sets of unique values | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of values in the computed union. - -## Usage - -<<< ./snippets/sunion-1.java - -> Callback response: - -```json -["union value1", "union value2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/sunion/snippets/sunion-1.java b/doc/2/core-classes/memory-storage/sunion/snippets/sunion-1.java deleted file mode 100644 index c3a11422..00000000 --- a/doc/2/core-classes/memory-storage/sunion/snippets/sunion-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.sunion(keys, new ResponseListener() { - @Override - public void onSuccess(String[] values) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/sunionstore/index.md b/doc/2/core-classes/memory-storage/sunionstore/index.md deleted file mode 100644 index 43c5d45d..00000000 --- a/doc/2/core-classes/memory-storage/sunionstore/index.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -code: true -type: page -title: sunionstore -description: MemoryStorage:sunionstore ---- - -# sunionstore - -Computes the union of the provided sets of unique values and stores the result in the `destination` key. - -If the destination key already exists, it is overwritten. - -[[_Redis documentation_]](https://redis.io/commands/sunionstore) - ---- - -## sunionstore(destination, keys, [options], callback) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------ | -| `destination` | string | Destination key identifier | -| `keys` | string | List of sets of unique values to intersect | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of elements in the stored union. - -## Usage - -<<< ./snippets/sunionstore-1.java - -> Callback response: - -```json -4 -``` diff --git a/doc/2/core-classes/memory-storage/sunionstore/snippets/sunionstore-1.java b/doc/2/core-classes/memory-storage/sunionstore/snippets/sunionstore-1.java deleted file mode 100644 index cefa5da2..00000000 --- a/doc/2/core-classes/memory-storage/sunionstore/snippets/sunionstore-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.sunionstore("destination", keys, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/time/index.md b/doc/2/core-classes/memory-storage/time/index.md deleted file mode 100644 index f5161a7b..00000000 --- a/doc/2/core-classes/memory-storage/time/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: time -description: MemoryStorage:time ---- - -# time - -Returns the current server time. - -[[_Redis documentation_]](https://redis.io/commands/time) - ---- - -## time([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array containing the following two items, in this order: - -- a timestamp in [Epoch time](https://en.wikipedia.org/wiki/Unix_time) -- the number of microseconds already elapsed in the current second - -## Usage - -<<< ./snippets/time-1.java - -> Callback response: - -```json -[1488791347, 494938] -``` diff --git a/doc/2/core-classes/memory-storage/time/snippets/time-1.java b/doc/2/core-classes/memory-storage/time/snippets/time-1.java deleted file mode 100644 index edf39d51..00000000 --- a/doc/2/core-classes/memory-storage/time/snippets/time-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.time(new ResponseListener() { - @Override - public void onSuccess(Long[] result) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/touch/index.md b/doc/2/core-classes/memory-storage/touch/index.md deleted file mode 100644 index 401ea608..00000000 --- a/doc/2/core-classes/memory-storage/touch/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -code: true -type: page -title: touch -description: MemoryStorage:touch ---- - -# touch - -Alters the last access time of one or multiple keys. A key is ignored if it does not exist. - -[[_Redis documentation_]](https://redis.io/commands/touch) - ---- - -## touch(keys, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------- | -| `keys` | array | List of keys to alter | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of altered keys. - -## Usage - -<<< ./snippets/touch-1.java - -> Callback response: - -```json -3 -``` diff --git a/doc/2/core-classes/memory-storage/touch/snippets/touch-1.java b/doc/2/core-classes/memory-storage/touch/snippets/touch-1.java deleted file mode 100644 index e5cf6365..00000000 --- a/doc/2/core-classes/memory-storage/touch/snippets/touch-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.touch(keys, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/ttl/index.md b/doc/2/core-classes/memory-storage/ttl/index.md deleted file mode 100644 index 8b87d34e..00000000 --- a/doc/2/core-classes/memory-storage/ttl/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: ttl -description: MemoryStorage:ttl ---- - -# ttl - -Returns the remaining time to live of a key, in seconds, or a negative value if the key does not exist or if it is persistent. - -[[_Redis documentation_]](https://redis.io/commands/ttl) - ---- - -## ttl(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the remaining time to live of the key, in seconds. - -## Usage - -<<< ./snippets/ttl-1.java - -> Callback response: - -```json -42 -``` diff --git a/doc/2/core-classes/memory-storage/ttl/snippets/ttl-1.java b/doc/2/core-classes/memory-storage/ttl/snippets/ttl-1.java deleted file mode 100644 index e934326d..00000000 --- a/doc/2/core-classes/memory-storage/ttl/snippets/ttl-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.ttl("key", new ResponseListener() { - @Override - public void onSuccess(int ttl) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/type/index.md b/doc/2/core-classes/memory-storage/type/index.md deleted file mode 100644 index cd556f8a..00000000 --- a/doc/2/core-classes/memory-storage/type/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: type -description: MemoryStorage:type ---- - -# type - -Returns the type of the value held by a key. - -[[_Redis documentation_]](https://redis.io/commands/type) - ---- - -## type(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns one of the following values: `hash`, `list`, `set`, `string`, `zset`. - -## Usage - -<<< ./snippets/type-1.java - -> Callback response: - -```json -"zset" -``` diff --git a/doc/2/core-classes/memory-storage/type/snippets/type-1.java b/doc/2/core-classes/memory-storage/type/snippets/type-1.java deleted file mode 100644 index 87414a34..00000000 --- a/doc/2/core-classes/memory-storage/type/snippets/type-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.type("key", new ResponseListener() { - @Override - public void onSuccess(String type) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zadd/index.md b/doc/2/core-classes/memory-storage/zadd/index.md deleted file mode 100644 index 12d4c733..00000000 --- a/doc/2/core-classes/memory-storage/zadd/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -code: true -type: page -title: zadd -description: MemoryStorage:zadd ---- - -# zadd - -Adds the specified elements to the sorted set stored at `key`. If the key does not exist, it is created, holding an empty sorted set. If it already exists and does not hold a sorted set, an error is returned. - -Scores are expressed as floating point numbers. - -If a member to insert is already in the sorted set, its score is updated and the member is reinserted at the right position in the set. - -[[_Redis documentation_]](https://redis.io/commands/zadd) - ---- - -## zadd(key, elements, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `key` | string | Key identifier | -| `elements` | array | List of JSON objects detailing the element to add to the sorted set.
Properties: `score` (element's score, `double`), `member` (element's value, `string`) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `ch` | boolean | Instead of returning the number of added allements, return the total number of changes performed (including updates) | `false` | -| `incr` | boolean | Instead of adding elements, increment the existing member with the provided `score` value. Only one score+element pair can be specified if this option is set | `false` | -| `nx` | boolean | Only add new elements, do not update existing ones | `false` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `xx` | boolean | Never add new elements, update only exiting ones | `false` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of elements added to the sorted set. - -## Usage - -<<< ./snippets/zadd-1.java - -> Callback response: - -```json -3 -``` diff --git a/doc/2/core-classes/memory-storage/zadd/snippets/zadd-1.java b/doc/2/core-classes/memory-storage/zadd/snippets/zadd-1.java deleted file mode 100644 index 4ef2d10e..00000000 --- a/doc/2/core-classes/memory-storage/zadd/snippets/zadd-1.java +++ /dev/null @@ -1,16 +0,0 @@ - -JSONObject[] elements = new JSONObject[]{ - new JSONObject().put("score", 1).put("member", "foo"), - new JSONObject().put("score", 2).put("member", "bar"), - new JSONObject().put("score", 3).put("member", "baz") -}; - -kuzzle.memoryStorage.zadd("key", elements new ResponseListener() { - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zcard/index.md b/doc/2/core-classes/memory-storage/zcard/index.md deleted file mode 100644 index 44a72dc2..00000000 --- a/doc/2/core-classes/memory-storage/zcard/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: zcard -description: MemoryStorage:zcard ---- - -# zcard - -Returns the number of elements held by a sorted set. - -[[_Redis documentation_]](https://redis.io/commands/zcard) - ---- - -## zcard(key, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of elements in a sorted set. - -## Usage - -<<< ./snippets/zcard-1.java - -> Callback response: - -```json -4 -``` diff --git a/doc/2/core-classes/memory-storage/zcard/snippets/zcard-1.java b/doc/2/core-classes/memory-storage/zcard/snippets/zcard-1.java deleted file mode 100644 index adfc20f5..00000000 --- a/doc/2/core-classes/memory-storage/zcard/snippets/zcard-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zcard("key", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zcount/index.md b/doc/2/core-classes/memory-storage/zcount/index.md deleted file mode 100644 index 650b9a44..00000000 --- a/doc/2/core-classes/memory-storage/zcount/index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -code: true -type: page -title: zcount -description: MemoryStorage:zcount ---- - -# zcount - -Returns the number of elements held by a sorted set with a score between the provided `min` and `max` values. - -By default, the provided min and max values are inclusive. This behavior can be changed using the syntax described in the Redis [ZRANGEBYSCORE](https://redis.io/commands/zrangebyscore) documentation. - -[[_Redis documentation_]](https://redis.io/commands/zcount) - ---- - -## zcount(key, min, max, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------ | -| `key` | string | Key identifier | -| `min` | int | Minimum score (inclusive by default) | -| `max` | int | Maximum score (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of elements in the provided score range. - -## Usage - -<<< ./snippets/zcount-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/zcount/snippets/zcount-1.java b/doc/2/core-classes/memory-storage/zcount/snippets/zcount-1.java deleted file mode 100644 index f5fe72bc..00000000 --- a/doc/2/core-classes/memory-storage/zcount/snippets/zcount-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zcount("key", 2, 3, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zincrby/index.md b/doc/2/core-classes/memory-storage/zincrby/index.md deleted file mode 100644 index 1a632b48..00000000 --- a/doc/2/core-classes/memory-storage/zincrby/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: zincrby -description: MemoryStorage:zincrby ---- - -# zincrby - -Increments the score of a `member` in a sorted set by the provided `value`. - -[[_Redis documentation_]](https://redis.io/commands/zincrby) - ---- - -## zincrby(key, member, increment, [options], [callback]) - -| Arguments | Type | Description | -| ----------- | ----------- | --------------------------- | -| `key` | string | Key identifier | -| `member` | string | Member element to increment | -| `increment` | double | Increment value | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns a double containing the updated member's score in the sorted set. - -## Usage - -<<< ./snippets/zincrby-1.java - -> Callback response: - -```json -4.14159 -``` diff --git a/doc/2/core-classes/memory-storage/zincrby/snippets/zincrby-1.java b/doc/2/core-classes/memory-storage/zincrby/snippets/zincrby-1.java deleted file mode 100644 index 5830ab5c..00000000 --- a/doc/2/core-classes/memory-storage/zincrby/snippets/zincrby-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zincrby("key", "foo", 3.14159, new ResponseListener() { - @Override - public void onSuccess(double value) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zinterstore/index.md b/doc/2/core-classes/memory-storage/zinterstore/index.md deleted file mode 100644 index 7012e550..00000000 --- a/doc/2/core-classes/memory-storage/zinterstore/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -code: true -type: page -title: zinterstore -description: MemoryStorage:zinterstore ---- - -# zinterstore - -Computes the intersection of the provided sorted sets and stores the result in the `destination` key. - -If the destination key already exists, it is overwritten. - -[[_Redis documentation_]](https://redis.io/commands/zinterstore) - ---- - -## zinterstore(destination, keys, [options], callback) - -| Arguments | Type | Description | -| ------------- | ----------- | -------------------------------- | -| `destination` | string | Destination key identifier | -| `keys` | string | List of sorted sets to intersect | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------- | ------- | ----------------------------------------------------------------------------------------------------------- | ------- | -| `aggregate` | string | Specify how members' scores are aggregated during the intersection.
Allowed values: `min`, `max`, `sum` | `sum` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `weights` | array | Specify a multiplication factor for each input sorted set | `[1]` | - ---- - -## Callback Response - -Returns an integer containing the number of members in the stored intersection. - -## Usage - -<<< ./snippets/zinterstore-1.java - -> Callback response: - -```json -4 -``` diff --git a/doc/2/core-classes/memory-storage/zinterstore/snippets/zinterstore-1.java b/doc/2/core-classes/memory-storage/zinterstore/snippets/zinterstore-1.java deleted file mode 100644 index 0eab45cd..00000000 --- a/doc/2/core-classes/memory-storage/zinterstore/snippets/zinterstore-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.zinterstore("destination", keys, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zlexcount/index.md b/doc/2/core-classes/memory-storage/zlexcount/index.md deleted file mode 100644 index 4befc45f..00000000 --- a/doc/2/core-classes/memory-storage/zlexcount/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: zlexcount -description: MemoryStorage:zlexcount ---- - -# zlexcount - -Counts elements in a sorted set where all members have equal score, using lexicographical ordering. The `min` and `max` values are inclusive by default. To change this behavior, please check the syntax detailed in the [Redis documentation](https://redis.io/commands/zrangebylex). - -[[_Redis documentation_]](https://redis.io/commands/zlexcount) - ---- - -## zlexcount(key, min, max, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------- | -| `key` | string | Key identifier | -| `min` | string | Minimum member value (inclusive by default) | -| `max` | string | Maximum member value (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the number of elements in the provided lexicographical value range. - -## Usage - -<<< ./snippets/zlexcount-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/zlexcount/snippets/zlexcount-1.java b/doc/2/core-classes/memory-storage/zlexcount/snippets/zlexcount-1.java deleted file mode 100644 index cb5f22b8..00000000 --- a/doc/2/core-classes/memory-storage/zlexcount/snippets/zlexcount-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zlexcount("key", "[b", "[f", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrange/index.md b/doc/2/core-classes/memory-storage/zrange/index.md deleted file mode 100644 index 69d15261..00000000 --- a/doc/2/core-classes/memory-storage/zrange/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -code: true -type: page -title: zrange -description: MemoryStorage:zrange ---- - -# zrange - -Returns elements from a sorted set depending on their position in the set, from a `start` position index to a `stop` position index (inclusives). -First position starts at `0`. - -[[_Redis documentation_]](https://redis.io/commands/zrange) - ---- - -## zrange(key, start, stop, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------- | -| `key` | string | Key identifier | -| `start` | int | Start position in the set (index starts at position `0`) | -| `stop` | int | End position in the set | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of objects, each containing the following properties: - -- `member`: member value in the sorted set -- `score`: member associated score - -## Usage - -<<< ./snippets/zrange-1.java - -> Callback response: - -```json -[ - { "member": "foo", "score": 1 }, - { "member": "bar", "score": 2 }, - { "member": "baz", "score": 3 } -] -``` diff --git a/doc/2/core-classes/memory-storage/zrange/snippets/zrange-1.java b/doc/2/core-classes/memory-storage/zrange/snippets/zrange-1.java deleted file mode 100644 index 94bd9aaf..00000000 --- a/doc/2/core-classes/memory-storage/zrange/snippets/zrange-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zrange("key", 0, -1, new ResponseListener() { - @Override - public void onSuccess(JSONObject[] members) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrangebylex/index.md b/doc/2/core-classes/memory-storage/zrangebylex/index.md deleted file mode 100644 index 3f8c2b5f..00000000 --- a/doc/2/core-classes/memory-storage/zrangebylex/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: zrangebylex -description: MemoryStorage:zrangebylex ---- - -# zrangebylex - -Returns elements in a sorted set where all members have equal score, using lexicographical ordering. The `min` and `max` values are inclusive by default. To change this behavior, please check the full documentation. - -[[_Redis documentation_]](https://redis.io/commands/zrangebylex) - ---- - -## zrangebylex(key, min, max, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------- | -| `key` | string | Key identifier | -| `min` | string | Minimum member value (inclusive by default) | -| `max` | string | Maximum member value (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `limit` | array | Limit the result set to a range of matching elements (similar to _SELECT LIMIT offset, count_ in SQL).
Format: `[, ]` | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of matching members. - -## Usage - -<<< ./snippets/zrangebylex-1.java - -> Callback response: - -```json -["member1", "member2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/zrangebylex/snippets/zrangebylex-1.java b/doc/2/core-classes/memory-storage/zrangebylex/snippets/zrangebylex-1.java deleted file mode 100644 index 90cfa2b4..00000000 --- a/doc/2/core-classes/memory-storage/zrangebylex/snippets/zrangebylex-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zrangebylex("key", "-", "(g", new ResponseListener() { - @Override - public void onSuccess(String[] members) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrangebyscore/index.md b/doc/2/core-classes/memory-storage/zrangebyscore/index.md deleted file mode 100644 index f32eb128..00000000 --- a/doc/2/core-classes/memory-storage/zrangebyscore/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -code: true -type: page -title: zrangebyscore -description: MemoryStorage:zrangebyscore ---- - -# zrangebyscore - -Returns all the elements in the sorted set at key with a score between `min` and `max` (inclusive). The elements are considered to be ordered from low to high scores. - -[[_Redis documentation_]](https://redis.io/commands/zrangebyscore) - ---- - -## zrangebyscore(key, min, max, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------ | -| `key` | string | Key identifier | -| `min` | double | Minimum score value (inclusive by default) | -| `max` | double | Maximum score value (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `limit` | array | Limit the result set to a range of matching elements (similar to _SELECT LIMIT offset, count_ in SQL).
Format: `[, ]` | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of matching members. - -## Usage - -<<< ./snippets/zrangebyscore-1.java - -> Callback response: - -```json -[ - { "member": "foo", "score": 1 }, - { "member": "bar", "score": 2 }, - { "member": "baz", "score": 3 } -] -``` diff --git a/doc/2/core-classes/memory-storage/zrangebyscore/snippets/zrangebyscore-1.java b/doc/2/core-classes/memory-storage/zrangebyscore/snippets/zrangebyscore-1.java deleted file mode 100644 index 5ae0e564..00000000 --- a/doc/2/core-classes/memory-storage/zrangebyscore/snippets/zrangebyscore-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zrangebyscore("key", 2, 3, new ResponseListener() { - @Override - public void onSuccess(JSONObject[] members) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrank/index.md b/doc/2/core-classes/memory-storage/zrank/index.md deleted file mode 100644 index 017913d9..00000000 --- a/doc/2/core-classes/memory-storage/zrank/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: zrank -description: MemoryStorage:zrank ---- - -# zrank - -Returns the position of an element in a sorted set, with scores in ascending order. The index returned is 0-based (the lowest score member has an index of 0). - -[[_Redis documentation_]](https://redis.io/commands/zrank) - ---- - -## zrank(key, member, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------ | -| `key` | string | Key identifier | -| `member` | string | Member of the sorted set | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the member's position in the sorted set. - -## Usage - -<<< ./snippets/zrank-1.java - -> Callback response: - -```json -0 -``` diff --git a/doc/2/core-classes/memory-storage/zrank/snippets/zrank-1.java b/doc/2/core-classes/memory-storage/zrank/snippets/zrank-1.java deleted file mode 100644 index cb688cc1..00000000 --- a/doc/2/core-classes/memory-storage/zrank/snippets/zrank-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zrank("key", "member", new ResponseListener() { - @Override - public void onSuccess(int position) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrem/index.md b/doc/2/core-classes/memory-storage/zrem/index.md deleted file mode 100644 index a1b2220c..00000000 --- a/doc/2/core-classes/memory-storage/zrem/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: zrem -description: MemoryStorage:zrem ---- - -# zrem - -Removes members from a sorted set. - -[[_Redis documentation_]](https://redis.io/commands/zrem) - ---- - -## zrem(key, members, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------- | -| `key` | string | Key identifier | -| `members` | array | List of members to remove | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of members removed from the sorted set. - -## Usage - -<<< ./snippets/zrem-1.java - -> Callback response: - -```json -3 -``` diff --git a/doc/2/core-classes/memory-storage/zrem/snippets/zrem-1.java b/doc/2/core-classes/memory-storage/zrem/snippets/zrem-1.java deleted file mode 100644 index 11918285..00000000 --- a/doc/2/core-classes/memory-storage/zrem/snippets/zrem-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] members = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.zrem("key", members, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zremrangebylex/index.md b/doc/2/core-classes/memory-storage/zremrangebylex/index.md deleted file mode 100644 index c4fb65d5..00000000 --- a/doc/2/core-classes/memory-storage/zremrangebylex/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: zremrangebylex -description: MemoryStorage:zremrangebylex ---- - -# zremrangebylex - -Removes members from a sorted set where all elements have the same score, using lexicographical ordering. The `min` and `max` interval are inclusive, see the [Redis documentation](https://redis.io/commands/zrangebylex) to change this behavior. - -[[_Redis documentation_]](https://redis.io/commands/zremrangebylex) - ---- - -## zremrangebylex(key, min, max, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------- | -| `key` | string | Key identifier | -| `min` | string | Minimum member value (inclusive by default) | -| `max` | string | Maximum member value (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of removed members from the sorted set. - -## Usage - -<<< ./snippets/zremrangebylex-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/zremrangebylex/snippets/zremrangebylex-1.java b/doc/2/core-classes/memory-storage/zremrangebylex/snippets/zremrangebylex-1.java deleted file mode 100644 index f11dbb98..00000000 --- a/doc/2/core-classes/memory-storage/zremrangebylex/snippets/zremrangebylex-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zremrangebylex("key", "[b", "(f", new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zremrangebyrank/index.md b/doc/2/core-classes/memory-storage/zremrangebyrank/index.md deleted file mode 100644 index 5631f7cf..00000000 --- a/doc/2/core-classes/memory-storage/zremrangebyrank/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -code: true -type: page -title: zremrangebyrank -description: MemoryStorage:zremrangebyrank ---- - -# zremrangebyrank - -Removes members from a sorted set with their position in the set between `start` and `stop` (inclusive). - -Positions are 0-based, meaning the first member of the set has a position of 0. - -[[_Redis documentation_]](https://redis.io/commands/zremrangebyrank) - ---- - -## zremrangebyrank(key, min, max, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------------- | -| `key` | string | Key identifier | -| `min` | int | Minimum position index (inclusive by default) | -| `max` | int | Maximum position index (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of removed members from the sorted set. - -## Usage - -<<< ./snippets/zremrangebyrank-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/zremrangebyrank/snippets/zremrangebyrank-1.java b/doc/2/core-classes/memory-storage/zremrangebyrank/snippets/zremrangebyrank-1.java deleted file mode 100644 index 1be4c978..00000000 --- a/doc/2/core-classes/memory-storage/zremrangebyrank/snippets/zremrangebyrank-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zremrangebyrank("key", 1, 2, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zremrangebyscore/index.md b/doc/2/core-classes/memory-storage/zremrangebyscore/index.md deleted file mode 100644 index 3b4a80de..00000000 --- a/doc/2/core-classes/memory-storage/zremrangebyscore/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: zremrangebyscore -description: MemoryStorage:zremrangebyscore ---- - -# zremrangebyscore - -Removes members from a sorted set with a score between `min` and `max` (inclusive by default). - -[[_Redis documentation_]](https://redis.io/commands/zremrangebyscore) - ---- - -## zremrangebyscore(key, min, max, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------ | -| `key` | string | Key identifier | -| `min` | double | Minimum score (inclusive by default) | -| `max` | double | Maximum score (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an integer containing the number of removed members from the sorted set. - -## Usage - -<<< ./snippets/zremrangebyscore-1.java - -> Callback response: - -```json -2 -``` diff --git a/doc/2/core-classes/memory-storage/zremrangebyscore/snippets/zremrangebyscore-1.java b/doc/2/core-classes/memory-storage/zremrangebyscore/snippets/zremrangebyscore-1.java deleted file mode 100644 index 583eaeba..00000000 --- a/doc/2/core-classes/memory-storage/zremrangebyscore/snippets/zremrangebyscore-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zremrangebyscore("key", 1, 2, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrevrange/index.md b/doc/2/core-classes/memory-storage/zrevrange/index.md deleted file mode 100644 index d2cde92c..00000000 --- a/doc/2/core-classes/memory-storage/zrevrange/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -code: true -type: page -title: zrevrange -description: MemoryStorage:zrevrange ---- - -# zrevrange - -Identical to [zrange](/sdk/java/2/core-classes/memory-storage/zrange), except that the sorted set is traversed in descending order. - -[[_Redis documentation_]](https://redis.io/commands/zrevrange) - ---- - -## zrevrange(key, start, stop, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------- | -| `key` | string | Key identifier | -| `start` | int | Start position in the set (index starts at position `0`) | -| `stop` | int | End position in the set | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of objects, each containing the following properties: - -- `member`: member value in the sorted set -- `score`: member associated score - -## Usage - -<<< ./snippets/zrevrange-1.java - -> Callback response: - -```json -[ - { "member": "baz", "score": 3 }, - { "member": "bar", "score": 2 }, - { "member": "foo", "score": 1 } -] -``` diff --git a/doc/2/core-classes/memory-storage/zrevrange/snippets/zrevrange-1.java b/doc/2/core-classes/memory-storage/zrevrange/snippets/zrevrange-1.java deleted file mode 100644 index 027d82ed..00000000 --- a/doc/2/core-classes/memory-storage/zrevrange/snippets/zrevrange-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zrevrange("key", 0, -1, new ResponseListener() { - @Override - public void onSuccess(JSONObject[] members) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrevrangebylex/index.md b/doc/2/core-classes/memory-storage/zrevrangebylex/index.md deleted file mode 100644 index 3eb4feac..00000000 --- a/doc/2/core-classes/memory-storage/zrevrangebylex/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: zrevrangebylex -description: MemoryStorage:zrevrangebylex ---- - -# zrevrangebylex - -Identical to [zrangebylex](/sdk/java/2/core-classes/memory-storage/zrangebylex) except that the sorted set is traversed in descending order. - -[[_Redis documentation_]](https://redis.io/commands/zrevrangebylex) - ---- - -## zrevrangebylex(key, min, max, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------- | -| `key` | string | Key identifier | -| `min` | string | Minimum member value (inclusive by default) | -| `max` | string | Maximum member value (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `limit` | array | Limit the result set to a range of matching elements (similar to _SELECT LIMIT offset, count_ in SQL).
Format: `[, ]` | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of matching members. - -## Usage - -<<< ./snippets/zrevrangebylex-1.java - -> Callback response: - -```json -["member1", "member2", "..."] -``` diff --git a/doc/2/core-classes/memory-storage/zrevrangebylex/snippets/zrevrangebylex-1.java b/doc/2/core-classes/memory-storage/zrevrangebylex/snippets/zrevrangebylex-1.java deleted file mode 100644 index c526d829..00000000 --- a/doc/2/core-classes/memory-storage/zrevrangebylex/snippets/zrevrangebylex-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zrevrangebylex("key", "-", "(g", new ResponseListener() { - @Override - public void onSuccess(String[] members) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrevrangebyscore/index.md b/doc/2/core-classes/memory-storage/zrevrangebyscore/index.md deleted file mode 100644 index 525aed8e..00000000 --- a/doc/2/core-classes/memory-storage/zrevrangebyscore/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -code: true -type: page -title: zrevrangebyscore -description: MemoryStorage:zrevrangebyscore ---- - -# zrevrangebyscore - -Identical to [zrangebyscore](/sdk/java/2/core-classes/memory-storage/zrangebyscore) except that the sorted set is traversed in descending order. - -[[_Redis documentation_]](https://redis.io/commands/zrevrangebyscore) - ---- - -## zrevrangebyscore(key, min, max, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------ | -| `key` | string | Key identifier | -| `min` | double | Minimum score value (inclusive by default) | -| `max` | double | Maximum score value (inclusive by default) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `limit` | array | Limit the result set to a range of matching elements (similar to _SELECT LIMIT offset, count_ in SQL).
Format: `[, ]` | `null` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return value - -Returns the `MemoryStorage` object to allow chaining. - ---- - -## Callback Response - -Returns an array of matching members. - -## Usage - -<<< ./snippets/zrevrangebyscore-1.java - -> Callback response: - -```json -[ - { "member": "baz", "score": 3 }, - { "member": "bar", "score": 2 }, - { "member": "foo", "score": 1 } -] -``` diff --git a/doc/2/core-classes/memory-storage/zrevrangebyscore/snippets/zrevrangebyscore-1.java b/doc/2/core-classes/memory-storage/zrevrangebyscore/snippets/zrevrangebyscore-1.java deleted file mode 100644 index 3bd7961b..00000000 --- a/doc/2/core-classes/memory-storage/zrevrangebyscore/snippets/zrevrangebyscore-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zrevrangebyscore("key", 2, 3, new ResponseListener() { - @Override - public void onSuccess(JSONObject[] members) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zrevrank/index.md b/doc/2/core-classes/memory-storage/zrevrank/index.md deleted file mode 100644 index 24abc5bf..00000000 --- a/doc/2/core-classes/memory-storage/zrevrank/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: zrevrank -description: MemoryStorage:zrevrank ---- - -# zrevrank - -Returns the position of an element in a sorted set, with scores in descending order. The index returned is 0-based (the lowest score member has an index of 0). - -[[_Redis documentation_]](https://redis.io/commands/zrevrank) - ---- - -## zrevrank(key, member, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------ | -| `key` | string | Key identifier | -| `member` | string | Member of the sorted set | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an integer containing the member's position in the sorted set. - -## Usage - -<<< ./snippets/zrevrank-1.java - -> Callback response: - -```json -0 -``` diff --git a/doc/2/core-classes/memory-storage/zrevrank/snippets/zrevrank-1.java b/doc/2/core-classes/memory-storage/zrevrank/snippets/zrevrank-1.java deleted file mode 100644 index acedf859..00000000 --- a/doc/2/core-classes/memory-storage/zrevrank/snippets/zrevrank-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zrevrank("key", "member", new ResponseListener() { - @Override - public void onSuccess(int position) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zscan/index.md b/doc/2/core-classes/memory-storage/zscan/index.md deleted file mode 100644 index 4a659e4c..00000000 --- a/doc/2/core-classes/memory-storage/zscan/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: zscan -description: MemoryStorage:zscan ---- - -# zscan - -Identical to [scan](/sdk/java/2/core-classes/memory-storage/scan), except that `zscan` iterates the members held by a sorted set. - -[[_Redis documentation_]](https://redis.io/commands/zscan) - ---- - -## zscan(key, cursor, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------------------------------------------------------------------- | -| `key` | string | Key identifier | -| `cursor` | int | Page number (iteration starts with a cursor value of `0`, and ends when the next cursor position is `0`) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------------------------------------- | ------- | -| `count` | int | Return the _approximate_ `count` number of items per result page | `10` | -| `match` | string | Search only for member values matching the provided pattern | `*` | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a JSON array containing 2 entries: - -- the cursor position for the next page of results (a next position of `0` indicates the end of the scan) -- an array of sorted set members and their associated scores - -## Usage - -<<< ./snippets/zscan-1.java - -> Callback response: - -```json -{ - "cursor": 18, - "values": ["member1", "member1's score", "member2", "member2's score", "..."] -} -``` diff --git a/doc/2/core-classes/memory-storage/zscan/snippets/zscan-1.java b/doc/2/core-classes/memory-storage/zscan/snippets/zscan-1.java deleted file mode 100644 index 6988fe4b..00000000 --- a/doc/2/core-classes/memory-storage/zscan/snippets/zscan-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zscan("key", 0, new ResponseListener() { - @Override - public void onSuccess(JSONObject page) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zscore/index.md b/doc/2/core-classes/memory-storage/zscore/index.md deleted file mode 100644 index b02a61ea..00000000 --- a/doc/2/core-classes/memory-storage/zscore/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: zscore -description: MemoryStorage:zscore ---- - -# zscore - -Returns the score of a member in a sorted set. - -[[_Redis documentation_]](https://redis.io/commands/zscore) - ---- - -## zscore(key, member, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------- | -| `key` | string | Key identifier | -| `member` | string | Sorted set member | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a floating point number containing the searched member's score. - -## Usage - -<<< ./snippets/zscore-1.java - -> Callback response: - -```json -1 -``` diff --git a/doc/2/core-classes/memory-storage/zscore/snippets/zscore-1.java b/doc/2/core-classes/memory-storage/zscore/snippets/zscore-1.java deleted file mode 100644 index 60e8b0df..00000000 --- a/doc/2/core-classes/memory-storage/zscore/snippets/zscore-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -kuzzle.memoryStorage.zscore("key", "bar", new ResponseListener() { - @Override - public void onSuccess(double score) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/memory-storage/zunionstore/index.md b/doc/2/core-classes/memory-storage/zunionstore/index.md deleted file mode 100644 index b9bdf05d..00000000 --- a/doc/2/core-classes/memory-storage/zunionstore/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -code: true -type: page -title: zunionstore -description: MemoryStorage:zunionstore ---- - -# zunionstore - -Computes the union of the provided sorted sets and stores the result in the `destination` key. - -If the destination key already exists, it is overwritten. - -[[_Redis documentation_]](https://redis.io/commands/zunionstore) - ---- - -## zunionstore(destination, keys, [options], callback) - -| Arguments | Type | Description | -| ------------- | ----------- | -------------------------------- | -| `destination` | string | Destination key identifier | -| `keys` | string | List of sorted sets to intersect | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------- | ------- | ----------------------------------------------------------------------------------------------------------- | ------- | -| `aggregate` | string | Specify how members' scores are aggregated during the intersection.
Allowed values: `min`, `max`, `sum` | `sum` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `weights` | array | Specify a multiplication factor for each input sorted set | `[1]` | - ---- - -## Callback Response - -Returns an integer containing the number of members in the stored union. - -## Usage - -<<< ./snippets/zunionstore-1.java - -> Callback response: - -```json -4 -``` diff --git a/doc/2/core-classes/memory-storage/zunionstore/snippets/zunionstore-1.java b/doc/2/core-classes/memory-storage/zunionstore/snippets/zunionstore-1.java deleted file mode 100644 index d173e4fd..00000000 --- a/doc/2/core-classes/memory-storage/zunionstore/snippets/zunionstore-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -String[] keys = new String[]{"key1", "key2", "..."}; - -kuzzle.memoryStorage.zunionstore("destination", keys, new ResponseListener() { - @Override - public void onSuccess(int count) { - // callback called once the action has completed - } - - @Override - public void onError(JSONObject error) { - } -}); diff --git a/doc/2/core-classes/profile/add-policy/index.md b/doc/2/core-classes/profile/add-policy/index.md deleted file mode 100644 index 13a9af36..00000000 --- a/doc/2/core-classes/profile/add-policy/index.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -code: true -type: page -title: addPolicy -description: Profile:addPolicy ---- - -# addPolicy - -Adds a role to the security profile. - -:::info -Updating a security profile will have no impact until the [save](/sdk/java/2/core-classes/profile/save) method is called -::: - ---- - -## addPolicy(id) - -| Arguments | Type | Description | -| --------- | ------ | -------------------------------------- | -| `id` | string | Unique id of the new role to associate | - ---- - -## addPolicy(policy) - -| Arguments | Type | Description | -| --------- | ----------- | ----------------------------------------------------------------------------- | -| `policy` | JSON Object | policy instance corresponding to the new associated role and its restrictions | - ---- - -## Return Value - -Returns the `Profile` object to allow chaining calls. - -## Usage - -<<< ./snippets/add-policy-1.java diff --git a/doc/2/core-classes/profile/add-policy/snippets/add-policy-1.java b/doc/2/core-classes/profile/add-policy/snippets/add-policy-1.java deleted file mode 100644 index 35280791..00000000 --- a/doc/2/core-classes/profile/add-policy/snippets/add-policy-1.java +++ /dev/null @@ -1,15 +0,0 @@ - -JSONObject policy = new JSONObject() - .put("roleId", "some role id") - .put("restrictedTo", new JSONArray() - .put(new JSONObject().put("index", "index1")) - .put(new JSONObject() - .put("index", "index2") - .put("collections", new JSONArray().put("foo").put("bar")) - ) - ); - -profile.addPolicy(policy); - -// you may also add a role ID directly -profile.addPolicy("some role id"); diff --git a/doc/2/core-classes/profile/constructor/index.md b/doc/2/core-classes/profile/constructor/index.md deleted file mode 100644 index b98090ee..00000000 --- a/doc/2/core-classes/profile/constructor/index.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -code: true -type: page -title: constructor -description: Profile:constructor -order: 1 ---- - -# Constructors - -Instantiates a new `Profile` object, representing a security [profile](/core/1/guides/essentials/security#users-profiles-and-roles), which is a set of one or many [Role](/sdk/java/2/core-classes/role) objects. - ---- - -## Profile(Security, id, content, [meta]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------------------------------- | -| `Security` | Security | An instantiated [Security](/sdk/java/2/core-classes/security) object | -| `id` | string | Unique profile identifier | -| `content` | JSON Object | Profile content | -| `meta` | JSON Object | Profile metadata | - -**Note:** this constructor won't make any call to Kuzzle. - ---- - -## Properties - -| Property name | Type | Description | get/set | -| ------------- | ----------- | ------------------------- | ------- | -| `content` | JSON object | Raw profile content | get | -| `id` | string | Unique profile identifier | get | -| `meta` | JSON object | Profile metadata | get | - ---- - -## Return Value - -Returns to the `Profile` object. - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/profile/constructor/snippets/constructor-1.java b/doc/2/core-classes/profile/constructor/snippets/constructor-1.java deleted file mode 100644 index fd09501f..00000000 --- a/doc/2/core-classes/profile/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,20 +0,0 @@ - -JSONObject policy1 = new JSONObject() - .put("roleId", "myrole"); - -JSONObject policy2 = new JSONObject() - .put("roleId", "default") - .put("restrictedTo", new JSONArray() - .put(new JSONObject().put("index", "index1")) - .put(new JSONObject() - .put("index", "index2") - .put("collections",new JSONArray().put("foo").put("bar")) - ) - ); -JSONObject roles = new JSONObject() - .put("policies", new JSONArray() - .put(policy1) - .put(policy2) - ); - -Profile profile = new Profile(kuzzle.security, "profileId", roles); diff --git a/doc/2/core-classes/profile/delete/index.md b/doc/2/core-classes/profile/delete/index.md deleted file mode 100644 index 74767586..00000000 --- a/doc/2/core-classes/profile/delete/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: delete -description: Profile:delete ---- - -# delete - -Deletes this security profile from Kuzzle. - ---- - -## delete([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the ID of the deleted profile. - -## Usage - -<<< ./snippets/delete-1.java diff --git a/doc/2/core-classes/profile/delete/snippets/delete-1.java b/doc/2/core-classes/profile/delete/snippets/delete-1.java deleted file mode 100644 index dfb9e6f4..00000000 --- a/doc/2/core-classes/profile/delete/snippets/delete-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -profile - .delete(new ResponseListener() { - @Override - public void onSuccess(String deleteId) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/profile/get-policies/index.md b/doc/2/core-classes/profile/get-policies/index.md deleted file mode 100644 index 785b5257..00000000 --- a/doc/2/core-classes/profile/get-policies/index.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -code: true -type: page -title: getPolicies -description: Profile:getPolicies ---- - -# getPolicies - -Returns roles associated to this security policy. - ---- - -## Return Value - -Returns an array of roles linked to this security policy. - -## Usage - -<<< ./snippets/get-policies-1.java - -> Callback response - -```json -[ - { - "roleId": "", - "restrictedTo": { - "index": "", - "collections": ["", "", "<...>"] - } - }, - { - "roleId": "" - }, - { - "roleId": "", - "restrictedTo": { - "index": "", - "collections": [""] - } - } -] -``` diff --git a/doc/2/core-classes/profile/get-policies/snippets/get-policies-1.java b/doc/2/core-classes/profile/get-policies/snippets/get-policies-1.java deleted file mode 100644 index 84b89df1..00000000 --- a/doc/2/core-classes/profile/get-policies/snippets/get-policies-1.java +++ /dev/null @@ -1,3 +0,0 @@ - -for(JSONObject policy : profile.getPolicies()) { -} diff --git a/doc/2/core-classes/profile/index.md b/doc/2/core-classes/profile/index.md deleted file mode 100644 index 996694ea..00000000 --- a/doc/2/core-classes/profile/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: Profile -description: Profile documentation ---- diff --git a/doc/2/core-classes/profile/save/index.md b/doc/2/core-classes/profile/save/index.md deleted file mode 100644 index 68d14949..00000000 --- a/doc/2/core-classes/profile/save/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: save -description: Profile:save ---- - -# save - -Creates or replaces the profile in Kuzzle. - -:::warning -Saving the object will return an error if the linked roles have not been previously created in Kuzzle. -::: - ---- - -## save([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Profile` object to allow chaining. - ---- - -## Callback Response - -Returns a `Profile` object. - -## Usage - -<<< ./snippets/save-1.java diff --git a/doc/2/core-classes/profile/save/snippets/save-1.java b/doc/2/core-classes/profile/save/snippets/save-1.java deleted file mode 100644 index e8abeeb1..00000000 --- a/doc/2/core-classes/profile/save/snippets/save-1.java +++ /dev/null @@ -1,32 +0,0 @@ - -JSONObject policy1 = new JSONObject() - .put("roleId", "myrole"); - -JSONObject policy2 = new JSONObject() - .put("roleId", "default") - .put("restrictedTo", new JSONArray() - .put(new JSONObject().put("index", "index1")) - .put(new JSONObject() - .put("index", "index2") - .put("collections",new JSONArray().put("foo").put("bar")) - ) - ); - -JSONObject roles = new JSONObject() - .put("policies", new JSONArray() - .put(policy1) - .put(policy2) - ); - -Profile profile = kuzzle.security.profile("myprofile", roles); - -profile.save(new ResponseListener() { - @Override - public void onSuccess(Profile savedProfile) { - - } - - @Overrid public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/profile/set-content/index.md b/doc/2/core-classes/profile/set-content/index.md deleted file mode 100644 index 8374e6f3..00000000 --- a/doc/2/core-classes/profile/set-content/index.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -code: true -type: page -title: setContent -description: Profile:setContent ---- - -# setContent - -Replaces the content of the `Profile` object. - -:::info -Updating a profile will have no impact until the `save` method is called -::: - ---- - -## setContent(data) - -| Arguments | Type | Description | -| --------- | ----------- | --------------- | -| `data` | JSON Object | Profile content | - ---- - -## Return Value - -Returns the `Profile` object. - -## Usage - -<<< ./snippets/set-content-1.java diff --git a/doc/2/core-classes/profile/set-content/snippets/set-content-1.java b/doc/2/core-classes/profile/set-content/snippets/set-content-1.java deleted file mode 100644 index 3ec8e775..00000000 --- a/doc/2/core-classes/profile/set-content/snippets/set-content-1.java +++ /dev/null @@ -1,21 +0,0 @@ - -JSONObject policy1 = new JSONObject() - .put("roleId", "myrole"); - -JSONObject policy2 = new JSONObject() - .put("roleId", "default") - .put("restrictedTo", new JSONArray() - .put(new JSONObject().put("index", "index1")) - .put(new JSONObject() - .put("index", "index2") - .put("collections",new JSONArray().put("foo").put("bar")) - ) - ); - -JSONObject newContent = new JSONObject() - .put("policies", new JSONArray() - .put(policy1) - .put(policy2) - ); - -profile.setContent(newRolesList); diff --git a/doc/2/core-classes/profile/set-policies/index.md b/doc/2/core-classes/profile/set-policies/index.md deleted file mode 100644 index f6a335b3..00000000 --- a/doc/2/core-classes/profile/set-policies/index.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -code: true -type: page -title: setPolicies -description: Profile:setPolicies ---- - -# setPolicies - -Replaces the roles associated with this security profile. - ---- - -## `setPolicies(Array policyIDs)` - -| Arguments | Type | Description | -| ----------- | ---------------- | ----------------- | -| `policyIDs` | array of strings | Policy IDs to add | - ---- - -## `setPolicies(Array policyDefinitions)` - -| Arguments | Type | Description | -| ------------------- | --------------------- | ------------------------- | -| `policyDefinitions` | array of JSON objects | Policy definitions to add | - ---- - -## Return Value - -Returns the `Profile` object. - -::: info -Updating a profile will have no impact until the `save` method is called -::: - -## Usage - -<<< ./snippets/set-policies-1.java diff --git a/doc/2/core-classes/profile/set-policies/snippets/set-policies-1.java b/doc/2/core-classes/profile/set-policies/snippets/set-policies-1.java deleted file mode 100644 index 0f5bb759..00000000 --- a/doc/2/core-classes/profile/set-policies/snippets/set-policies-1.java +++ /dev/null @@ -1,10 +0,0 @@ - -// Binding role IDs to a profile -profile.setPolicies(new String[]{"role1 ID", "role2 ID", "role3 ID"}); - -// Binding policies definition to a profile -profile.setPolicies(new JSONObject[]{ - new JSONObject().put('roleId', 'role1 ID'), - new JSONObject().put('roleId', 'role2 ID'), - new JSONObject().put('roleId', 'role3 ID') -}); diff --git a/doc/2/core-classes/profile/update/index.md b/doc/2/core-classes/profile/update/index.md deleted file mode 100644 index 371e1f1c..00000000 --- a/doc/2/core-classes/profile/update/index.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -code: true -type: page -title: update -description: Profile:update ---- - -# update - -Performs a partial content update on this object. - ---- - -## update(content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------- | -| `content` | JSON Object | Profile content | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Profile` object to allow chaining. - ---- - -## Callback Response - -Returns the updated version of this object. - -## Usage - -<<< ./snippets/update-1.java diff --git a/doc/2/core-classes/profile/update/snippets/update-1.java b/doc/2/core-classes/profile/update/snippets/update-1.java deleted file mode 100644 index e31f284b..00000000 --- a/doc/2/core-classes/profile/update/snippets/update-1.java +++ /dev/null @@ -1,17 +0,0 @@ - -JSONObject policy1 = new JSONObject().put("roleId", "myrole"); - -JSONObject updateContent = new JSONObject() - .put("policies", new JSONArray().put(policy1)); - -profile.update(updateContent, new ResponseListener() { - @Override - public void onSuccess(Profile updatedProfile) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/role/constructor/index.md b/doc/2/core-classes/role/constructor/index.md deleted file mode 100644 index 0c3d223a..00000000 --- a/doc/2/core-classes/role/constructor/index.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -code: true -type: page -title: constructor -description: Role:constructor -order: 1 ---- - -# Constructors - -Instantiates a new `Role` object, which defines a set of right policies. - ---- - -## Role(Security, id, content, [meta]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------------------------------- | -| `Security` | Security | An instantiated [Security](/sdk/java/2/core-classes/security) object | -| `id` | string | Unique role identifier | -| `content` | JSON Object | Role content | -| `meta` | JSON Object | Role metadata | - -**Note:** this constructor won't make any call to Kuzzle. - ---- - -## Properties - -| Property name | Type | Description | get/set | -| ------------- | ----------- | ------------------------- | ------- | -| `content` | JSON object | Raw role content | get | -| `id` | string | Unique profile identifier | get | -| `meta` | JSON object | Role metadata | get | - ---- - -## Return Value - -Returns the `Role` object. - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/role/constructor/snippets/constructor-1.java b/doc/2/core-classes/role/constructor/snippets/constructor-1.java deleted file mode 100644 index 740f55c8..00000000 --- a/doc/2/core-classes/role/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -JSONObject roleDefinition = new JSONObject() - .put("controllers", new JSONObject() - .put("*", new JSONObject() - .put("actions", new JSONObject() - .put("*", true) - ) - ) - ) -); - -Role role = new Role(kuzzle.security, "role ID", roleDefinition); diff --git a/doc/2/core-classes/role/delete/index.md b/doc/2/core-classes/role/delete/index.md deleted file mode 100644 index 52fb1235..00000000 --- a/doc/2/core-classes/role/delete/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: delete -description: Role:delete ---- - -# delete - -Deletes the role from Kuzzle. - ---- - -## delete([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the ID of the deleted role. - -## Usage - -<<< ./snippets/delete-1.java diff --git a/doc/2/core-classes/role/delete/snippets/delete-1.java b/doc/2/core-classes/role/delete/snippets/delete-1.java deleted file mode 100644 index df0bf65a..00000000 --- a/doc/2/core-classes/role/delete/snippets/delete-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -role.delete(new ResponseListener() { - @Override - public void onSuccess(String deletedId) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/role/index.md b/doc/2/core-classes/role/index.md deleted file mode 100644 index f0d01c2e..00000000 --- a/doc/2/core-classes/role/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: Role -description: Role documentation ---- diff --git a/doc/2/core-classes/role/save/index.md b/doc/2/core-classes/role/save/index.md deleted file mode 100644 index b51ae7be..00000000 --- a/doc/2/core-classes/role/save/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -code: true -type: page -title: save -description: Role:save ---- - -# save - -Creates or replaces the role in Kuzzle's database layer. - ---- - -## save([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Role` object to allow chaining. - ---- - -## Callback Response - -Returns a `Role` object. - -## Usage - -<<< ./snippets/save-1.java diff --git a/doc/2/core-classes/role/save/snippets/save-1.java b/doc/2/core-classes/role/save/snippets/save-1.java deleted file mode 100644 index f2f1689b..00000000 --- a/doc/2/core-classes/role/save/snippets/save-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -role.save(new ResponseListener { - @Override - public void onSuccess(Role savedRole) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/role/set-content/index.md b/doc/2/core-classes/role/set-content/index.md deleted file mode 100644 index f2154b49..00000000 --- a/doc/2/core-classes/role/set-content/index.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -code: true -type: page -title: setContent -description: Role:setContent ---- - -# setContent - -Replaces the content of the `Role` object. - -:::info -Updating a role content will have no impact until the [save](/sdk/java/2/core-classes/role/save) method is called -::: - ---- - -## setContent(data) - -| Arguments | Type | Description | -| --------- | ----------- | ------------ | -| `data` | JSON Object | Role content | - ---- - -## Return Value - -Returns the `Role` object. - -## Usage - -<<< ./snippets/set-content-1.java diff --git a/doc/2/core-classes/role/set-content/snippets/set-content-1.java b/doc/2/core-classes/role/set-content/snippets/set-content-1.java deleted file mode 100644 index 9cdbf3ae..00000000 --- a/doc/2/core-classes/role/set-content/snippets/set-content-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -JSONObject roleDefinition = new JSONObject() - .put("controllers", new JSONObject() - .put("*", new JSONObject() - .put("actions", new JSONObject() - .put("*", true) - ) - ) - ) -); - -role.setContent(roleDefinition); diff --git a/doc/2/core-classes/role/update/index.md b/doc/2/core-classes/role/update/index.md deleted file mode 100644 index c951bce2..00000000 --- a/doc/2/core-classes/role/update/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -code: true -type: page -title: update -description: Role:update ---- - -# update - -Updates the role object in Kuzzle. - -:::warning -Unlike a regular document update, this method will replace the whole role definition under the indexes node with the `updateContent` parameter. -In other words, you always need to provide the complete role definition in the `updateContent` object. - -This method has the same effect as calling [setContent](/sdk/java/2/core-classes/role/set-content) followed by the [save](/sdk/java/2/core-classes/role/save) method. -::: - -To get more information about Kuzzle permissions, please refer to our [permissions guide](/core/1/guides/essentials/security#user-permissions). - ---- - -## update(content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------- | -| `content` | JSON Object | New role content | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `Role` object to allow chaining. - ---- - -## Callback Response - -Returns the updated version of this object. - -## Usage - -<<< ./snippets/update-1.java diff --git a/doc/2/core-classes/role/update/snippets/update-1.java b/doc/2/core-classes/role/update/snippets/update-1.java deleted file mode 100644 index 28ac63c9..00000000 --- a/doc/2/core-classes/role/update/snippets/update-1.java +++ /dev/null @@ -1,22 +0,0 @@ - -JSONObject roleDefinition = new JSONObject() - .put("controllers", new JSONObject() - .put("document", new JSONObject() - .put("actions", new JSONObject() - .put("get", true) - ) - ) - ) -); - -role.update(roleDefinition, new ResponseListener() { - @Override - public void onSuccess(Role updatedRole) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/room/constructor/index.md b/doc/2/core-classes/room/constructor/index.md deleted file mode 100644 index 976e5978..00000000 --- a/doc/2/core-classes/room/constructor/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -code: true -type: page -title: constructor -description: Room:constructor -order: 1 ---- - -# Constructors - -The `Room` object is the result of a subscription request, allowing you to manipulate the subscription itself. - ---- - -## Room(Collection, [options]) - -| Arguments | Type | Description | -| ------------ | ------ | ---------------------------------------- | -| `Collection` | object | an instantiated Kuzzle Collection object | -| `options` | object | Optional subscription configuration | - ---- - -## Options - -| Option | Type | Description | Default | -| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| `volatile` | JSON Object | Additional information passed to notifications to other users | `null` | -| `scope` | string | Filter [document notifications](/sdk/java/2/essentials/realtime-notifications#document-notification) depending on their scope status. You may receive entering documents (scope: `in`), leaving documents (scope: `out`), all documents changes (scope: `all`) or filter these notifications completely (scope: `none`). This filter does not affect pub/sub messages or user events. | `all` | -| `state` | string | Filter [document notifications](/sdk/java/2/essentials/realtime-notifications#document-notification) depending on the state of the modifying request. You may receive real-time notifications when a document is about to be changed (state: `pending`), or be notified when the change has been fully written in the database (state: `done`), or both (state: `all`). This filter does not affect pub/sub messages or user events. | `done` | -| `subscribeToSelf` | boolean | (Don't) subscribe to notifications fired as a consequence of our own queries | `true` | -| `users` | string | Filter [user notifications](/sdk/java/2/essentials/realtime-notifications#user-notification) triggered upon a user entering the room (user: `in`), leaving the room (user: `out`), or both (user: `all`). Setting this variable to `none` prevents receiving these notifications | `none` | - ---- - -## Properties - -| Property name | Type | Description | get/set | -| ----------------- | ----------- | ---------------------------------------------------------------------------- | ------- | -| `collection` | string | The subscribed collection | get | -| `filters` | JSON object | The current set of filters of this room | get/set | -| `headers` | JSON Object | Common headers for all sent documents. | get/set | -| `volatile` | JSON Object | Additional information passed to notifications to other users | get/set | -| `subscribeToSelf` | boolean | (Don't) subscribe to notifications fired as a consequence of our own queries | get/set | -| `roomId` | string | Unique room identifier | get | - -**Notes:** - -- the `headers` property is inherited from the provided `Collection` object and can be overridden -- updating the `volatile` property takes effect only after the subscription is renewed -- by default, the global `volatile` properties are sent along with the subscription request. If a `volatile` option is provided during subscription, it will be merged with the global `volatile` for the subscription only. In case of conflicts, subscription `volatile` data takes priority over the global `volatile` ones. - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/room/constructor/snippets/constructor-1.java b/doc/2/core-classes/room/constructor/snippets/constructor-1.java deleted file mode 100644 index a9c633c7..00000000 --- a/doc/2/core-classes/room/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,5 +0,0 @@ - -Room room = new Room(dataCollection); - -RoomOptions options = new RoomOptions().setSubscribeToSelf(false); -Room room = new Room(dataCollection, options); diff --git a/doc/2/core-classes/room/count/index.md b/doc/2/core-classes/room/count/index.md deleted file mode 100644 index 9982097b..00000000 --- a/doc/2/core-classes/room/count/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -code: true -type: page -title: count -description: Room:count ---- - -# count - -Returns the number of subscribers in the room. - ---- - -## count(callback) - -| Arguments | Type | Description | -| ---------- | -------- | ------------------------------ | -| `callback` | function | Callback handling the response | - ---- - -## Callback Response - -Returns an `integer` containing the number of users subscribing to this room. - -## Usage - -<<< ./snippets/count-1.java - -> Callback response - -```json -1 -``` diff --git a/doc/2/core-classes/room/count/snippets/count-1.java b/doc/2/core-classes/room/count/snippets/count-1.java deleted file mode 100644 index eb1162e1..00000000 --- a/doc/2/core-classes/room/count/snippets/count-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -room.count(new ResponseListener() { - @Override - public void onSuccess(Integer result) throws Exception { - // ... - } - - @Override - public void onError(JSONObject error) throws Exception { - // Handle error - } -}); diff --git a/doc/2/core-classes/room/index.md b/doc/2/core-classes/room/index.md deleted file mode 100644 index acee84a3..00000000 --- a/doc/2/core-classes/room/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: Room -description: Room documentation ---- diff --git a/doc/2/core-classes/room/renew/index.md b/doc/2/core-classes/room/renew/index.md deleted file mode 100644 index a30a9d5e..00000000 --- a/doc/2/core-classes/room/renew/index.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -code: true -type: page -title: renew -description: Room:renew ---- - -# renew - -Renew the subscription. Force a new subscription using the same filters if no new ones are provided. - -Unsubscribes first if this `Room` object was already listening to events. - ---- - -## renew([filters], notificationCallback, subscriptionCallback) - -| Arguments | Type | Description | -| ---------------------- | ----------- | ------------------------------------------------------------------------------------------------ | -| `filters` | JSON Object | [Filters](/core/1/guides/cookbooks/realtime-api) | -| `notificationCallback` | function | Function called each time a [notification](/sdk/java/2/essentials/realtime-notifications) is received | -| `subscriptionCallback` | function | Function called with the subscription result | - -## Usage - -<<< ./snippets/renew-1.java diff --git a/doc/2/core-classes/room/renew/snippets/renew-1.java b/doc/2/core-classes/room/renew/snippets/renew-1.java deleted file mode 100644 index 24449954..00000000 --- a/doc/2/core-classes/room/renew/snippets/renew-1.java +++ /dev/null @@ -1,49 +0,0 @@ - -JSONObject filter = new JSONObject() - .put("and", new JSONArray() - .put( - new JSONObject().put("in", - new JSONObject().put("status", - new JSONArray() - .put("idle") - .put("wantToHire") - .put("toHire") - .put("riding") - ) - ) - ) - .put( - new JSONObject().put("in", - new JSONObject() - .put("type", new JSONArray().put("cab")) - ) - ) - .put( - new JSONObject().put("geoDistance", - new JSONObject() - .put("distance", "10km") - .put("pos", - new JSONObject() - .put("lat", "48.8566140") - .put("lon", "2.352222") - ) - ) - ) - ); - -room.renew(filters, new ResponseListener() { - @Override - public void onSuccess(NotificationResponse result) throws Exception { - // called each time a change is detected on documents matching this filter - - // check the Room/Notifications section of this documentation - // to get notification examples - } - - @Override - public void onError(JSONObject error) throws Exception { - // Handle error - } -}, new ResponseListener() { - // Handle the subscription result -}); diff --git a/doc/2/core-classes/room/set-headers/index.md b/doc/2/core-classes/room/set-headers/index.md deleted file mode 100644 index 35d5e6b8..00000000 --- a/doc/2/core-classes/room/set-headers/index.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -code: true -type: page -title: setHeaders -description: Room:setHeaders ---- - -# setHeaders - -> Returns itself - -This is a helper function returning itself, allowing to easily chain calls. - ---- - -## setHeaders(content, [replace]) - -| Arguments | Type | Description | -| --------- | ----------- | ------------------------------------------------------------------------- | -| `content` | JSON Object | New content | -| `replace` | boolean | true: replace the current content with the provided data, false: merge it | - -**Note:** by default, the `replace` argument is set to `false` - ---- - -## Return value - -Returns this `Room` object to allow chaining. - -## Usage - -<<< ./snippets/set-headers-1.java diff --git a/doc/2/core-classes/room/set-headers/snippets/set-headers-1.java b/doc/2/core-classes/room/set-headers/snippets/set-headers-1.java deleted file mode 100644 index ca09ea47..00000000 --- a/doc/2/core-classes/room/set-headers/snippets/set-headers-1.java +++ /dev/null @@ -1,4 +0,0 @@ - -JSONObject headers = new JSONObject(); -headers.put("someContent", "someValue"); -room.setHeaders(headers, true); diff --git a/doc/2/core-classes/room/unsubscribe/index.md b/doc/2/core-classes/room/unsubscribe/index.md deleted file mode 100644 index 15a6c543..00000000 --- a/doc/2/core-classes/room/unsubscribe/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -code: true -type: page -title: unsubscribe -description: Room:unsubscribe ---- - -# unsubscribe - -Cancels the current subscription. - ---- - -## Return value - -Returns this `Room` object to allow chaining. - -## Usage - -<<< ./snippets/unsubscribe-1.java diff --git a/doc/2/core-classes/room/unsubscribe/snippets/unsubscribe-1.java b/doc/2/core-classes/room/unsubscribe/snippets/unsubscribe-1.java deleted file mode 100644 index 52bce96c..00000000 --- a/doc/2/core-classes/room/unsubscribe/snippets/unsubscribe-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -room.unsubscribe(); diff --git a/doc/2/core-classes/search-result/constructor/index.md b/doc/2/core-classes/search-result/constructor/index.md deleted file mode 100644 index 23db326b..00000000 --- a/doc/2/core-classes/search-result/constructor/index.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -code: true -type: page -title: constructor -description: SearchResult:constructor -order: 1 ---- - -# Constructor - -This object can only be instantiated internally by this SDK, and is an easy-to-use representation of a paginated result from a [search](/sdk/java/2/core-classes/collection/search) or a [scroll](/sdk/java/2/core-classes/collection/scroll) request. - ---- - -## Properties - -| Property name | Type | Description | get/set | -| -------------- | ---------- | --------------------------------------------------------- | ------- | -| `aggregations` | object | The result of an aggregation produced by a search request | get | -| `collection` | Collection | The collection associated to this document | get | -| `documents` | Document[] | An array of instantiated Document objects | get | -| `fetched` | number | The number of fetched documents so far | get/set | -| `options` | object | The arguments of the search/scroll request | get | -| `filters` | object | The filters of the search request | get | -| `total` | integer | The total number of results that can be fetched | get | - ---- diff --git a/doc/2/core-classes/search-result/fetch-next/index.md b/doc/2/core-classes/search-result/fetch-next/index.md deleted file mode 100644 index c92875e9..00000000 --- a/doc/2/core-classes/search-result/fetch-next/index.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -code: true -type: page -title: fetchNext -description: SearchResult:fetchNext ---- - -# fetchNext - -Fetches the next SearchResult, by triggering a new search/scroll request depending on the options and filters of the SearchResult. - -If the previous request was a search or a scroll action which provided a `scroll` argument, -`fetchNext` will use the `scrollId` retrieved from the current result to make a new scroll request. - -If the previous request was a search action which provided `size` argument and `sort` filtering, -`fetchNext` will use Elasticsearch's [`search_after`](https://www.elastic.co/guide/en/elasticsearch/reference/7.5/search-request-body.html#request-body-search-search-after) mechanism, which can efficiently search through a large volume of documents, bypassing internal hard limits\[1\], -but at the cost of reflecting the latest changes of the index, as opposed to using scroll. - -If the previous request was a search action which provided `from` and `size` arguments, -`fetchNext` will add `size` to `from` and make a new search request. - ---- - -## How to process every document of a collection - -The safest way to process all documents in a collection is to fetch them as a batch in order to avoid memory exhaustion and possibly hitting some hard limits\[1\] on the database layer. - -:::warning -Make sure your first search request includes the `size` and `scroll` parameters -::: - -:::info -\[1\] Elasticsearch limits the number of documents inside a single page to [10,000 by default](https://www.elastic.co/guide/en/elasticsearch/reference/5.6/index-modules.html#dynamic-index-settings). -::: - -## Usage - -<<< ./snippets/fetch-next-1.java - -<<< ./snippets/fetch-next-2.java diff --git a/doc/2/core-classes/search-result/fetch-next/snippets/fetch-next-1.java b/doc/2/core-classes/search-result/fetch-next/snippets/fetch-next-1.java deleted file mode 100644 index e6b8e262..00000000 --- a/doc/2/core-classes/search-result/fetch-next/snippets/fetch-next-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -searchResult.fetchNext(new ResponseListener() { - @Override - public void onSuccess(SearchResult nextSearchResult) { - // called once the fetchNext action has been completed - // nextSearchResult is an instantiated SearchResult object - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -}); diff --git a/doc/2/core-classes/search-result/fetch-next/snippets/fetch-next-2.java b/doc/2/core-classes/search-result/fetch-next/snippets/fetch-next-2.java deleted file mode 100644 index ae1f884a..00000000 --- a/doc/2/core-classes/search-result/fetch-next/snippets/fetch-next-2.java +++ /dev/null @@ -1,37 +0,0 @@ - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; - -Kuzzle kuzzle = new Kuzzle("localhost"); - -JSONObject filter = new JSONObject(); - -Options options = new Options(); -options.setFrom((long) 0); -options.setSize((long) 1000); -options.setScroll("30s"); - -ResponseListener listener = new ResponseListener() { - @Override - public void onSuccess(SearchResult searchResult) { - if (searchResult == null) { - return; - } - - for (Document doc : searchResult.getDocuments()) { - // do something with the document - // this.processDocument(doc); - } - - searchResult.fetchNext(this); - } - - @Override - public void onError(JSONObject error) { - // handle errors here - } -}; - -kuzzle - .collection("collection", "index") - .search(filter, options, listener); diff --git a/doc/2/core-classes/search-result/index.md b/doc/2/core-classes/search-result/index.md deleted file mode 100644 index 9d05e1bd..00000000 --- a/doc/2/core-classes/search-result/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: SearchResult -description: SearchResult documentation ---- diff --git a/doc/2/core-classes/security/constructor/index.md b/doc/2/core-classes/security/constructor/index.md deleted file mode 100644 index 6316ea02..00000000 --- a/doc/2/core-classes/security/constructor/index.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -code: true -type: page -title: constructor -description: Security:constructor -order: 1 ---- - -# Constructor - -The Security component lets you handle user permissions in Kuzzle. - -Please refer to our [permissions guide](/core/1/guides/essentials/security#user-permissions) for more information. - ---- - -## Security - -| Arguments | Type | Description | -| --------- | ------ | -------------------------------------------------------------------- | -| `Kuzzle` | object | An instantiated [Kuzzle](/sdk/java/2/core-classes/kuzzle) object | - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/security/constructor/snippets/constructor-1.java b/doc/2/core-classes/security/constructor/snippets/constructor-1.java deleted file mode 100644 index 7a7e5f51..00000000 --- a/doc/2/core-classes/security/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,6 +0,0 @@ - -// using the static instance -Security security = kuzzle.security; - -// or instantiating a new Security object -Security security = new Security(kuzzle); diff --git a/doc/2/core-classes/security/create-credentials/index.md b/doc/2/core-classes/security/create-credentials/index.md deleted file mode 100644 index b1107419..00000000 --- a/doc/2/core-classes/security/create-credentials/index.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -code: true -type: page -title: createCredentials -description: Security:createCredentials ---- - -# createCredentials - -Create credentials of user with `kuid` for the specified `strategy`. - ---- - -## createCredentials(strategy, kuid, credentials, [options], [callback]) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------ | -| `strategy` | string | Strategy you want to create credentials in | -| `kuid` | string | User's kuid | -| `credentials` | JSON object | The credentials | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object with the created credentials. - -## Usage - -<<< ./snippets/create-credentials-1.java - -> Callback response - -```json -{ - "username": "foo", - "kuid": "" -} -``` diff --git a/doc/2/core-classes/security/create-credentials/snippets/create-credentials-1.java b/doc/2/core-classes/security/create-credentials/snippets/create-credentials-1.java deleted file mode 100644 index b13e1560..00000000 --- a/doc/2/core-classes/security/create-credentials/snippets/create-credentials-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -JSONObject credentials = new JSONObject().put("username", "bar"); - -kuzzle.security.createCredentials("local", "kuid", credentials, new ResponseListener() { - @Override - public void onSuccess(JSONObject credentials) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/security/create-profile/index.md b/doc/2/core-classes/security/create-profile/index.md deleted file mode 100644 index bf484502..00000000 --- a/doc/2/core-classes/security/create-profile/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: createProfile -description: Security:createProfile ---- - -# createProfile - -Create a new profile in Kuzzle. - -:::info -There is a small delay between profile creation and its availability in our search layer (usually a couple of seconds). -That means that a profile that was just created might not be immediately returned by the `searchProfiles` function. -::: - ---- - -## createProfile(id, content, [options], callback) - -| Arguments | Type | Description | -| ---------- | --------------------- | ----------------------------------------- | -| `id` | string | Unique profile identifier | -| `policies` | array of JSON objects | List of policies to apply to this profile | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `replaceIfExist` | boolean | If the same profile already exists: throw an error if sets to false. Replace the existing profile otherwise | `false` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Callback Response - -Returns a security [Profile](/sdk/java/2/core-classes/profile) object. - -## Usage - -<<< ./snippets/create-profile-1.java diff --git a/doc/2/core-classes/security/create-profile/snippets/create-profile-1.java b/doc/2/core-classes/security/create-profile/snippets/create-profile-1.java deleted file mode 100644 index 4d094d1d..00000000 --- a/doc/2/core-classes/security/create-profile/snippets/create-profile-1.java +++ /dev/null @@ -1,29 +0,0 @@ - -JSONObject[] policies = new JSONObject[]{ - new JSONObject().put("roleId", "myrole"), - new JSONObject() - .put("roleId", "default") - .put("restrictedTo", new JSONArray() - .put(new JSONObject().put("index", "index1")) - .put(new JSONObject() - .put("index", "index2") - .put("collections",new JSONArray().put("foo").put("bar")) - ) - ) -}; - -Options opts = new Options().setReplaceIfExist(true); - -kuzzle - .security - .createProfile("myprofile", policies, opts, new ResponseListener() { - @Override - public void onSuccess(Profile profile) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/create-restricted-user/index.md b/doc/2/core-classes/security/create-restricted-user/index.md deleted file mode 100644 index 39d20706..00000000 --- a/doc/2/core-classes/security/create-restricted-user/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: createRestrictedUser -description: Security:createRestrictedUser ---- - -# createRestrictedUser - -Create a new restricted user in Kuzzle. -This function allows anonymous users to create a "restricted" user with predefined rights. - -:::info -There is a small delay between user creation and its availability in our search layer (usually a couple of seconds). -That means that a user that was just created may not be immediately returned by the `searchUsers` function. -::: - ---- - -## createRestrictedUser(id, content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------ | -| `id` | string | Unique user identifier, will be used as username | -| `content` | JSON Object | A plain JSON object representing the user | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer indexation to return (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Callback response - -Resolves to a [User](/sdk/java/2/core-classes/user) object. - -## Usage - -<<< ./snippets/create-restricted-user-1.java diff --git a/doc/2/core-classes/security/create-restricted-user/snippets/create-restricted-user-1.java b/doc/2/core-classes/security/create-restricted-user/snippets/create-restricted-user-1.java deleted file mode 100644 index 1eaaecca..00000000 --- a/doc/2/core-classes/security/create-restricted-user/snippets/create-restricted-user-1.java +++ /dev/null @@ -1,28 +0,0 @@ - -JSONObject content = new JSONObject(); - -JSONObject newUser = new JSONObject().put("content", content); - -JSONObject credentials = new JSONObject() - .put("local", new JSONObject() - // The "local" authentication strategy requires a password - .put("password", "secret password") - .put("lastLoggedIn", 1494411803)); - -newUser.put("credentials", credentials); - -Options opts = new Options().setReplaceIfExist(true); - -kuzzle - .security - .createUser("myNewUser", newUser, opts, new ResponseListener() { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/create-role/index.md b/doc/2/core-classes/security/create-role/index.md deleted file mode 100644 index 8af2b187..00000000 --- a/doc/2/core-classes/security/create-role/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: createRole -description: Security:createRole ---- - -# createRole - -Create a new role in Kuzzle. - -:::info -There is a small delay between role creation and its availability in our search layer (usually a couple of seconds). -That means that a role that was just created may not be immediately returned by the `searchRole` function. -::: - ---- - -## createRole(id, content, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `id` | string | Unique role identifier | -| `content` | JSON Object | A plain JSON object representing the role | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `replaceIfExist` | boolean | If the same role already exists: throw an error if sets to false. Replace the existing role otherwise | `false` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Callback Response - -Returns a [Role](/sdk/java/2/core-classes/role) object. - -## Usage - -<<< ./snippets/create-role-1.java diff --git a/doc/2/core-classes/security/create-role/snippets/create-role-1.java b/doc/2/core-classes/security/create-role/snippets/create-role-1.java deleted file mode 100644 index 57062c93..00000000 --- a/doc/2/core-classes/security/create-role/snippets/create-role-1.java +++ /dev/null @@ -1,26 +0,0 @@ - -JSONObject roleDefinition = new JSONObject() - .put("controllers", new JSONObject() - .put("*", new JSONObject() - .put("actions", new JSONObject() - .put("*", true) - ) - ) - ) -); - -Options opts = new Options().setReplaceIfExist(true); - -kuzzle - .security - .createRole("myrole", roleDefinition, opts, new ResponseListener() { - @Override - public void onSuccess(Role role) { - // the result is an instantiated Role object - } - - @Override - public void onError(JSONObject error) { - - } - }) diff --git a/doc/2/core-classes/security/create-user/index.md b/doc/2/core-classes/security/create-user/index.md deleted file mode 100644 index f069c560..00000000 --- a/doc/2/core-classes/security/create-user/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -code: true -type: page -title: createUser -description: Security:createUser ---- - -# createUser - -Create a new user in Kuzzle. - -:::info -There is a small delay between user creation and its availability in our search layer (usually a couple of seconds). -That means that a user that was just created might not be returned immediately by the `searchUsers` function. -::: - ---- - -## createUser(id, user, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------- | -| `id` | string | [Unique user identifier](/core/1/guides/essentials/user-authentication#kuzzle-user-identifier-kuid) | -| `user` | JSON Object | A plain JSON object representing the user (see below) | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | Callback handling the response | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - -The `user` object to provide must have the following properties: - -- `content` (JSON object): user global properties - - This object must contain a `profileIds` properties, an array of strings listing the security [profiles](/core/1/guides/essentials/security#users-profiles-and-roles) to be attached to the new user - - Any other property will be copied as additional global user information -- `credentials` (JSON object): a description of how the new user can identify themselves on Kuzzle - - Any number of credentials can be added, each one being an object with name equal to the [authentication strategy](/core/1/plugins/guides/strategies#exposing-authentication-strategies) used to authenticate the user, and with the login data as content. - - If this object is left empty, the user will be created in Kuzzle but the will not be able to login. - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a [User](/sdk/java/2/core-classes/user) object. - -## Usage - -<<< ./snippets/create-user-1.java diff --git a/doc/2/core-classes/security/create-user/snippets/create-user-1.java b/doc/2/core-classes/security/create-user/snippets/create-user-1.java deleted file mode 100644 index 6f51922e..00000000 --- a/doc/2/core-classes/security/create-user/snippets/create-user-1.java +++ /dev/null @@ -1,38 +0,0 @@ - -JSONObject content = new JSONObject() - // A "profileIds" field is required to bind a user to existing profiles - .put("profileIds", new JSONArray() - .put("admin") - ) - // You can also set custom fields to your user - .put("firstname", "John") - .put("lastname", "Doe"); - -JSONObject newUser = new JSONObject().put("content", content); - -JSONObject credentials = new JSONObject() - // Authentication strategy to use - .put("local", new JSONObject() - // The necessary information to provide vary, - // depending on the chosen authentication strategy - .put("password", "secret password") - .put("username", "jdoe") - ); - -newUser.put("credentials", credentials); - -Options opts = new Options(); - -kuzzle - .security - .createUser("myNewUser", newUser, opts, new ResponseListener() { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/delete-credentials/index.md b/doc/2/core-classes/security/delete-credentials/index.md deleted file mode 100644 index 93addf55..00000000 --- a/doc/2/core-classes/security/delete-credentials/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -code: true -type: page -title: deleteCredentials -description: Security:deleteCredentials ---- - -# deleteCredentials - -Delete current user's credentials for the specified `strategy`. - ---- - -## deleteCredentials(strategy, kuid, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | -------------------------------------------- | -| `strategy` | string | Strategy you want to delete credentials from | -| `kuid` | string | User's kuid | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object reflecting the query status. - -## Usage - -<<< ./snippets/delete-credentials-1.java - -> Callback response - -```json -{ - "acknowledged": true -} -``` diff --git a/doc/2/core-classes/security/delete-credentials/snippets/delete-credentials-1.java b/doc/2/core-classes/security/delete-credentials/snippets/delete-credentials-1.java deleted file mode 100644 index 1d1d0ee6..00000000 --- a/doc/2/core-classes/security/delete-credentials/snippets/delete-credentials-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.security.deleteCredentials("local", "kuid", new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/security/delete-profile/index.md b/doc/2/core-classes/security/delete-profile/index.md deleted file mode 100644 index 20df30e1..00000000 --- a/doc/2/core-classes/security/delete-profile/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -code: true -type: page -title: deleteProfile -description: Security:deleteProfile ---- - -# deleteProfile - -Delete the provided profile. - -:::info -There is a small delay between the time a profile is deleted and it being reflected in the search layer (usually a couple of seconds). -That means that a profile that was just deleted might still be returned by the `searchProfiles` function. -::: - ---- - -## deleteProfile(id, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `id` | string | Unique profile identifier to delete | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Security` object to allow chaining. - ---- - -## Callback Response - -Returns the ID of the security profile that has been deleted. - -## Usage - -<<< ./snippets/delete-profile-1.java - -> Callback response - -```json -"deleted profile identifier" -``` diff --git a/doc/2/core-classes/security/delete-profile/snippets/delete-profile-1.java b/doc/2/core-classes/security/delete-profile/snippets/delete-profile-1.java deleted file mode 100644 index 5c48727f..00000000 --- a/doc/2/core-classes/security/delete-profile/snippets/delete-profile-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .security - .deleteProfile("myprofile", new ResponseListener() { - @Override - public void onSuccess(String profileName) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/delete-role/index.md b/doc/2/core-classes/security/delete-role/index.md deleted file mode 100644 index 84470bc4..00000000 --- a/doc/2/core-classes/security/delete-role/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -code: true -type: page -title: deleteRole -description: Security:deleteRole ---- - -# deleteRole - -Delete the provided role. - -:::info -There is a small delay between the time a role is deleted and it being reflected in the search layer (usually a couple of seconds). -That means that a role that was just deleted might still be returned by the `searchRoles` function. -::: - ---- - -## deleteRole(id, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `id` | string | Unique role identifier to delete | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Security` object to allow chaining. - ---- - -## Callback Response - -Returns the id of the rold that has been deleted. - -## Usage - -<<< ./snippets/delete-role-1.java - -> Callback response - -```json -"deleted role identifier" -``` diff --git a/doc/2/core-classes/security/delete-role/snippets/delete-role-1.java b/doc/2/core-classes/security/delete-role/snippets/delete-role-1.java deleted file mode 100644 index a23f999f..00000000 --- a/doc/2/core-classes/security/delete-role/snippets/delete-role-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .security - .deleteRole("myrole", new ResponseListener() { - @Override - public void onSuccess(String roleName) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/delete-user/index.md b/doc/2/core-classes/security/delete-user/index.md deleted file mode 100644 index 8e631ac3..00000000 --- a/doc/2/core-classes/security/delete-user/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -code: true -type: page -title: deleteUser -description: Security:deleteUser ---- - -# deleteUser - -Delete the provided user. - -:::info -There is a small delay between the time a user is deleted and it being reflected in the search layer (usually a couple of seconds). -That means that a user that has just been deleted might still be returned by the `searchUsers` function. -::: - ---- - -## deleteUser(id, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `id` | string | Unique user identifier to delete | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Security` object to allow chaining. - ---- - -## Callback Response - -Return the id of the user that has been deleted. - -## Usage - -<<< ./snippets/delete-user-1.java - -> Callback response - -```json -"deleted user identifier" -``` diff --git a/doc/2/core-classes/security/delete-user/snippets/delete-user-1.java b/doc/2/core-classes/security/delete-user/snippets/delete-user-1.java deleted file mode 100644 index e203abca..00000000 --- a/doc/2/core-classes/security/delete-user/snippets/delete-user-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .security - .deleteUser("myuser", new ResponseListener() { - @Override - public void onSuccess(String userName) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/fetch-profile/index.md b/doc/2/core-classes/security/fetch-profile/index.md deleted file mode 100644 index 185f7afd..00000000 --- a/doc/2/core-classes/security/fetch-profile/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -code: true -type: page -title: fetchProfile -description: Security:fetchProfile ---- - -# fetchProfile - -Fetches a single stored profile using its unique ID. - ---- - -## fetchProfile(id, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `id` | string | Unique profile identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a security [Profile](/sdk/java/2/core-classes/profile) object. - -## Usage - -<<< ./snippets/fetch-profile-1.java diff --git a/doc/2/core-classes/security/fetch-profile/snippets/fetch-profile-1.java b/doc/2/core-classes/security/fetch-profile/snippets/fetch-profile-1.java deleted file mode 100644 index b9beb3a4..00000000 --- a/doc/2/core-classes/security/fetch-profile/snippets/fetch-profile-1.java +++ /dev/null @@ -1,15 +0,0 @@ - - -kuzzle - .security - .fetchProfile("myprofile", new ResponseListener() { - @Override - public void onSuccess(Profile profile) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/fetch-role/index.md b/doc/2/core-classes/security/fetch-role/index.md deleted file mode 100644 index b07e64a6..00000000 --- a/doc/2/core-classes/security/fetch-role/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -code: true -type: page -title: fetchRole -description: Security:fetchRole ---- - -# fetchRole - -Fetches a single stored role using its unique ID. - ---- - -## fetchRole(id, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `id` | string | Unique role identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a [Role](/sdk/java/2/core-classes/role) object. - -## Usage - -<<< ./snippets/fetch-role-1.java diff --git a/doc/2/core-classes/security/fetch-role/snippets/fetch-role-1.java b/doc/2/core-classes/security/fetch-role/snippets/fetch-role-1.java deleted file mode 100644 index 3a5d21cf..00000000 --- a/doc/2/core-classes/security/fetch-role/snippets/fetch-role-1.java +++ /dev/null @@ -1,15 +0,0 @@ - - -kuzzle - .security - .fetchRole("myrole", new ResponseListener() { - @Override - public void onSuccess(Role role) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/fetch-user/index.md b/doc/2/core-classes/security/fetch-user/index.md deleted file mode 100644 index d0a6439b..00000000 --- a/doc/2/core-classes/security/fetch-user/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -code: true -type: page -title: fetchUser -description: Security:fetchUser ---- - -# fetchUser - -Fetches a single stored user using its unique ID. - ---- - -## fetchUser(id, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `id` | string | Unique user identifier | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a [User](/sdk/java/2/core-classes/user) object. - -## Usage - -<<< ./snippets/fetch-user-1.java diff --git a/doc/2/core-classes/security/fetch-user/snippets/fetch-user-1.java b/doc/2/core-classes/security/fetch-user/snippets/fetch-user-1.java deleted file mode 100644 index a8f73d93..00000000 --- a/doc/2/core-classes/security/fetch-user/snippets/fetch-user-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .security - .fetchUser("myuser", new ResponseListener() { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/get-all-credential-fields/index.md b/doc/2/core-classes/security/get-all-credential-fields/index.md deleted file mode 100644 index 04544e14..00000000 --- a/doc/2/core-classes/security/get-all-credential-fields/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -code: true -type: page -title: getAllCredentialFields -description: Security:getAllCredentialFields ---- - -# getAllCredentialFields - -Fetches a list of accepted fields per authentication strategy. - ---- - -## getAllCredentialFields([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object with the credential fields. - -## Usage - -<<< ./snippets/get-all-credential-fields-1.java - -> Callback response: - -```json -{ - "local": ["kuid", "username"] -} -``` diff --git a/doc/2/core-classes/security/get-all-credential-fields/snippets/get-all-credential-fields-1.java b/doc/2/core-classes/security/get-all-credential-fields/snippets/get-all-credential-fields-1.java deleted file mode 100644 index 14b8a8e6..00000000 --- a/doc/2/core-classes/security/get-all-credential-fields/snippets/get-all-credential-fields-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.security.getAllCredentialFields(new ResponseListener() { - @Override - public void onSuccess(JSONObject strategies) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/security/get-credentials-fields/index.md b/doc/2/core-classes/security/get-credentials-fields/index.md deleted file mode 100644 index 0305efa5..00000000 --- a/doc/2/core-classes/security/get-credentials-fields/index.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -code: true -type: page -title: getCredentialsFields -description: Security:getCredentialsFields ---- - -# getCredentialFields - -Get credential information for the specified `strategy`. - ---- - -## getCredentialFields(strategy, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `strategy` | string | Strategy you want to get credentials from | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -The result is a an array of credential fields. - -## Usage - -<<< ./snippets/get-credentials-fields-1.java - -> Callback response: - -```json -["kuid", "username"] -``` diff --git a/doc/2/core-classes/security/get-credentials-fields/snippets/get-credentials-fields-1.java b/doc/2/core-classes/security/get-credentials-fields/snippets/get-credentials-fields-1.java deleted file mode 100644 index 97021d8b..00000000 --- a/doc/2/core-classes/security/get-credentials-fields/snippets/get-credentials-fields-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.security.getCredentialFields("local", new ResponseListener() { - @Override - public void onSuccess(String[] fields) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/security/get-credentials/index.md b/doc/2/core-classes/security/get-credentials/index.md deleted file mode 100644 index b4527150..00000000 --- a/doc/2/core-classes/security/get-credentials/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: getCredentials -description: Security:getCredentials ---- - -# getCredentials - -Get credential information of user with `kuid` for the specified `strategy`. - ---- - -## getCredentials(strategy, kuid, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `strategy` | string | Strategy you want to get credentials from | -| `kuid` | string | User's kuid | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -The result is a an object with the credentials. - -## Usage - -<<< ./snippets/get-credentials-1.java - -> Callback response - -```json -{ - "username": "foo", - "kuid": "" -} -``` diff --git a/doc/2/core-classes/security/get-credentials/snippets/get-credentials-1.java b/doc/2/core-classes/security/get-credentials/snippets/get-credentials-1.java deleted file mode 100644 index d7760617..00000000 --- a/doc/2/core-classes/security/get-credentials/snippets/get-credentials-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.security.getCredentials("local", "kuid", new ResponseListener() { - @Override - public void onSuccess(JSONObject credentials) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/security/get-user-rights/index.md b/doc/2/core-classes/security/get-user-rights/index.md deleted file mode 100644 index 1bd08450..00000000 --- a/doc/2/core-classes/security/get-user-rights/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -code: true -type: page -title: getUserRights -description: Security:getUserRights ---- - -# getUserRights - -> Callback response example - -```json -[ - { - "controller": "my-controller", - "action": "my-action", - "index": "*", - "collection": "*", - "value": "allowed" - }, - { - "controller": "another-controller", - "action": "*", - "index": "my-index", - "collection": "*", - "value": "conditional" - } -] -``` - -Given a Kuzzle user id (`kuid`), retrieves the list of permissions granted to that user. - ---- - -### getUserRights(id, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------- | -| `kuid` | String | [Kuzzle User Unique Identifier](/core/1/guides/essentials/user-authentication#kuzzle-user-identifier-kuid) | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -### Callback Response - -Returns an array of objects. - -## Usage - -<<< ./snippets/get-user-rights-1.java diff --git a/doc/2/core-classes/security/get-user-rights/snippets/get-user-rights-1.java b/doc/2/core-classes/security/get-user-rights/snippets/get-user-rights-1.java deleted file mode 100644 index 5c2ffadd..00000000 --- a/doc/2/core-classes/security/get-user-rights/snippets/get-user-rights-1.java +++ /dev/null @@ -1,15 +0,0 @@ - - -kuzzle - .security - .getUserRights("kuid", new ResponseListener() { - @Override - public void onSuccess(JSONObject[] rights) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/has-credentials/index.md b/doc/2/core-classes/security/has-credentials/index.md deleted file mode 100644 index 05c4d411..00000000 --- a/doc/2/core-classes/security/has-credentials/index.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -code: true -type: page -title: hasCredentials -description: Security:hasCredentials ---- - -# hasCredentials - -Checks if a user has credentials for the provided strategy. - ---- - -## hasCredentials(strategy, kuid, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------- | -| `strategy` | string | Strategy to check for credentials | -| `kuid` | JSON object | User's kuid | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a boolean value. - -## Usage - -<<< ./snippets/has-credentials-1.java diff --git a/doc/2/core-classes/security/has-credentials/snippets/has-credentials-1.java b/doc/2/core-classes/security/has-credentials/snippets/has-credentials-1.java deleted file mode 100644 index e12845e2..00000000 --- a/doc/2/core-classes/security/has-credentials/snippets/has-credentials-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -kuzzle.security.hasCredentials("local", "kuid", new ResponseListener() { - @Override - public void onSuccess(Boolean result) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/security/index.md b/doc/2/core-classes/security/index.md deleted file mode 100644 index 5cdb0b71..00000000 --- a/doc/2/core-classes/security/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: Security -description: Security documentation ---- diff --git a/doc/2/core-classes/security/is-action-allowed/index.md b/doc/2/core-classes/security/is-action-allowed/index.md deleted file mode 100644 index 219cec03..00000000 --- a/doc/2/core-classes/security/is-action-allowed/index.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -code: true -type: page -title: isActionAllowed -description: Security:isActionAllowed ---- - -# isActionAllowed - -Specifies if an action is allowed, denied or conditional based on the rights provided as the first argument: - -- `allowed` is returned when an action is authorized without condition -- `conditional` is returned when the authorization depends on a closure -- `denied` is returned when the action is forbidden - -An action is defined as a pair of action and controller (mandatory), plus an index and a collection(optional). - -:::info -You can get the rights from Kuzzle by using [Security.getUserRights](/sdk/java/2/core-classes/security/get-user-rights) and [Kuzzle.getMyRights](/sdk/java/2/core-classes/kuzzle/get-my-rights). -::: - ---- - -## isActionAllowed(rights, controller, action, index, collection) - -| Arguments | Type | Description | -| ------------ | ---------- | -------------- | -| `rights` | JSON array | Rights list | -| `controller` | String | The controller | -| `action` | String | The action | -| `index` | String | The index | -| `collection` | String | The collection | - ---- - -## Return Value - -Returns either `allowed`, `denied` or `conditional`. - -## Usage - -<<< ./snippets/is-action-allowed-1.java diff --git a/doc/2/core-classes/security/is-action-allowed/snippets/is-action-allowed-1.java b/doc/2/core-classes/security/is-action-allowed/snippets/is-action-allowed-1.java deleted file mode 100644 index 1eaf8b25..00000000 --- a/doc/2/core-classes/security/is-action-allowed/snippets/is-action-allowed-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle.security.getMyRights(new ResponseListener() { - @Override - public void onSuccess(JSONObject[] rights) { - // Policies is an enum with the following properties: - // allowed, denied, conditional - Policies authorization = kuzzle.security.isActionAllowed(rights, "read", "get", "index1", "collection1"); - } - - @Override - public void onError(JSONObject error) { - // ... - } -}); diff --git a/doc/2/core-classes/security/profile/index.md b/doc/2/core-classes/security/profile/index.md deleted file mode 100644 index 92656560..00000000 --- a/doc/2/core-classes/security/profile/index.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -code: true -type: page -title: profile -description: Security:profile ---- - -# profile - -Instantiate a new security [Profile](/sdk/java/2/core-classes/profile) object. - ---- - -## profile(id, content) - -| Arguments | Type | Description | -| --------- | ----------- | ------------------------- | -| `id` | string | Unique profile identifier | -| `content` | JSON Object | Profile content | - ---- - -## Return Value - -Returns the new security [Profile](/sdk/java/2/core-classes/profile) object. - -## Usage - -<<< ./snippets/profile-1.java diff --git a/doc/2/core-classes/security/profile/snippets/profile-1.java b/doc/2/core-classes/security/profile/snippets/profile-1.java deleted file mode 100644 index 496345f4..00000000 --- a/doc/2/core-classes/security/profile/snippets/profile-1.java +++ /dev/null @@ -1,20 +0,0 @@ - -JSONObject policy1 = new JSONObject() - .put("roleId", "myrole"); - -JSONObject policy2 = new JSONObject() - .put("roleId", "default") - .put("restrictedTo", new JSONArray() - .put(new JSONObject().put("index", "index1")) - .put(new JSONObject() - .put("index", "index2") - .put("collections",new JSONArray().put("foo").put("bar")) - ) - ); -JSONObject profileDefinition = new JSONObject() - .put("policies", new JSONArray() - .put(policy1) - .put(policy2) - ); - -Profile profile = kuzzle.security.profile("myprofile", profileDefinition); diff --git a/doc/2/core-classes/security/replace-user/index.md b/doc/2/core-classes/security/replace-user/index.md deleted file mode 100644 index 66afc110..00000000 --- a/doc/2/core-classes/security/replace-user/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: replaceUser -description: Security:replaceUser ---- - -# replaceUser - -Replaces an existing user. - ---- - -## replaceUser(id, content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------------------------------------------------------------------ | -| `id` | string | Unique user identifier | -| `content` | JSON Object | A plain JSON object representing the user, should contain the mandatory `profileIds` field | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Security` object to allow chaining. - ---- - -## Callback Response - -Returns a [User](/sdk/java/2/core-classes/user) object. - -## Usage - -<<< ./snippets/replace-user-1.java diff --git a/doc/2/core-classes/security/replace-user/snippets/replace-user-1.java b/doc/2/core-classes/security/replace-user/snippets/replace-user-1.java deleted file mode 100644 index 42cd6f2b..00000000 --- a/doc/2/core-classes/security/replace-user/snippets/replace-user-1.java +++ /dev/null @@ -1,21 +0,0 @@ - -JSONObject newContent = new JSONObject() - .put("profileIds", new JSONArray() - .put("admin") - ) - .put("firstname", "My Name Is") - .put("lastname", "Jonas"); - -kuzzle - .security - .replaceUser("User ID", newContent, new ResponseListener() { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/role/index.md b/doc/2/core-classes/security/role/index.md deleted file mode 100644 index aa830dbb..00000000 --- a/doc/2/core-classes/security/role/index.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -code: true -type: page -title: role -description: Security:role ---- - -# role - -Instantiate a new [Role](/sdk/java/2/core-classes/role) object. - ---- - -## role(id, content) - -| Arguments | Type | Description | -| --------- | ----------- | ---------------------- | -| `id` | string | Unique role identifier | -| `content` | JSON Object | Role content | - ---- - -## Return Value - -Returns the new [Role](/sdk/java/2/core-classes/role) object. - -## Usage - -<<< ./snippets/role-1.java diff --git a/doc/2/core-classes/security/role/snippets/role-1.java b/doc/2/core-classes/security/role/snippets/role-1.java deleted file mode 100644 index 8cb273b3..00000000 --- a/doc/2/core-classes/security/role/snippets/role-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -JSONObject roleDefinition = new JSONObject() - .put("controllers", new JSONObject() - .put("*", new JSONObject() - .put("actions", new JSONObject() - .put("*", true) - ) - ) - ) -); - -Role role = kuzzle.security.role("myrole", roleDefinition); diff --git a/doc/2/core-classes/security/scroll-profiles/index.md b/doc/2/core-classes/security/scroll-profiles/index.md deleted file mode 100644 index 15d44150..00000000 --- a/doc/2/core-classes/security/scroll-profiles/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -code: true -type: page -title: scrollProfiles -description: Security:scrollProfiles ---- - -# scrollProfiles - -Scrolls on stored profiles using the provided scroll ID. - ---- - -## scrollProfiles(scrollId, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------- | -| `scrollId` | string | Scroll identifier retrieved from a search query | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the list of fetched security profiles according to the scroll parameters (offset, limit etc.). - -## Usage - -<<< ./snippets/scroll-profiles-1.java diff --git a/doc/2/core-classes/security/scroll-profiles/snippets/scroll-profiles-1.java b/doc/2/core-classes/security/scroll-profiles/snippets/scroll-profiles-1.java deleted file mode 100644 index 8987b747..00000000 --- a/doc/2/core-classes/security/scroll-profiles/snippets/scroll-profiles-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .security - .scrollProfiles(scrollId, options, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList response) { - // called once the scroll action has been completed - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/security/scroll-users/index.md b/doc/2/core-classes/security/scroll-users/index.md deleted file mode 100644 index 9d564b97..00000000 --- a/doc/2/core-classes/security/scroll-users/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -code: true -type: page -title: scrollUsers -description: Security:scrollUsers ---- - -# scrollUsers - -Scrolls on stored users using the provided scroll ID. - ---- - -## scrollUsers(scrollId, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------- | -| `scrollId` | string | Scroll identifier retrieved from a search query | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns the list of fetched users according to the scroll parameters (offset, limit etc.). - -## Usage - -<<< ./snippets/scroll-users-1.java diff --git a/doc/2/core-classes/security/scroll-users/snippets/scroll-users-1.java b/doc/2/core-classes/security/scroll-users/snippets/scroll-users-1.java deleted file mode 100644 index 5cc6eef9..00000000 --- a/doc/2/core-classes/security/scroll-users/snippets/scroll-users-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -kuzzle - .security - .scrollUsers(scrollId, options, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList response) { - // called once the scroll action has been completed - } - - @Override - public void onError(JSONObject error) { - // Handle error - } - }); diff --git a/doc/2/core-classes/security/search-profiles/index.md b/doc/2/core-classes/security/search-profiles/index.md deleted file mode 100644 index ca327176..00000000 --- a/doc/2/core-classes/security/search-profiles/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -code: true -type: page -title: searchProfiles -description: Security:searchProfiles ---- - -# searchProfiles - -Search for security profiles, optionally returning only those linked to the provided list of security roles. - ---- - -## searchProfiles(filters, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `filters` | JSON Object | Search query | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `from` | number | Starting offset | `0` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `scroll` | string | Start a scroll session, with a time to live equals to this parameter's value following the [Elastisearch time format](https://www.elastic.co/guide/en/elasticsearch/reference/5.0/common-options.html#time-units) | `undefined` | -| `size` | integer | Number of hits to return per page | `10` | - ---- - -## Filters - -| Filter | Type | Description | Default | -| ------- | ----- | ------------------------------------------------ | ------- | -| `roles` | array | Contains an array `roles` with a list of role id | `[]` | - ---- - -## Callback Response - -Returns a JSON Object - -## Usage - -<<< ./snippets/search-profiles-1.java - -> Callback response: - -```json -{ - "total": 124, - "profiles": [ - // array of Profile objects - ], - // only if a scroll parameter has been provided - "scrollId": "" -} -``` diff --git a/doc/2/core-classes/security/search-profiles/snippets/search-profiles-1.java b/doc/2/core-classes/security/search-profiles/snippets/search-profiles-1.java deleted file mode 100644 index 8884481a..00000000 --- a/doc/2/core-classes/security/search-profiles/snippets/search-profiles-1.java +++ /dev/null @@ -1,35 +0,0 @@ - -// optional: search only for profiles referring the listed roles -JSONObject filters = new JSONObject() - .put("roles", new JSONArray().put("myrole").put("admin")); - -// optional: result pagination configuration -Options options = new Options(); -options.setFrom((long) 0); -options.setSize((long) 42); -options.setScroll("1m"); - - -kuzzle - .security - .searchProfiles(filters, options, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList profiles) { - // Contains a profiles list - for(Profile profile : profiles.getDocuments()) { - - } - - // Total number of profiles, regardless of pagination - long total = profiles.getTotal(); - - // Available only if a "scroll" option has been provided - String scrollId = profiles.getScroll() - } - - @Override - public void onError(JSONObject error) { - - } - }); - diff --git a/doc/2/core-classes/security/search-roles/index.md b/doc/2/core-classes/security/search-roles/index.md deleted file mode 100644 index 00ab2cc7..00000000 --- a/doc/2/core-classes/security/search-roles/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -code: true -type: page -title: searchRoles -description: Security:searchRoles ---- - -# searchRoles - -Search for security roles, optionally returning only the roles giving access to the provided controller names. - ---- - -## searchRoles(filters, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ---------------------------------------------------------------------------------------------------- | -| `filters` | JSON Object | Optionally contains a "controllers" array listing the controller names used to filter searched roles | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Filters - -| Filter | Type | Description | Default | -| ------------- | ----- | --------------------------------------------------------- | ------- | -| `controllers` | array | retrieve only roles allowing access to the provided names | `[]` | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ---------------------------------- | ------- | -| `from` | number | Starting offset | `0` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `size` | number |  Number of hits to return per page | `10` | - ---- - -## Callback Response - -Return a JSON Object - -## Usage - -<<< ./snippets/search-roles-1.java - -> Callback response: - -```json -{ - "total": 124, - "roles": [ - // array of Role - ] -} -``` diff --git a/doc/2/core-classes/security/search-roles/snippets/search-roles-1.java b/doc/2/core-classes/security/search-roles/snippets/search-roles-1.java deleted file mode 100644 index 5daed381..00000000 --- a/doc/2/core-classes/security/search-roles/snippets/search-roles-1.java +++ /dev/null @@ -1,29 +0,0 @@ - -// optional: retrieve only roles allowing access to the -// provided controller names -JSONObject filter = new JSONObject() - .put("controllers", new JSONArray() - .put("document") - .put("security") - ); - -// optional: result pagination configuration -Options options = new Options(); -options.setFrom((long) 0); -options.setSize((long) 42); -options.setScroll("1m"); - -kuzzle - .security - .searchRoles(filter, options, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList roles) { - // roles.getDocuments() returns a roles list - for(Role role : roles.getDocuments()) { - - } - - // roles.getTotal() returns the number of matched roles, regardless of pagination - roles.getTotal(); - } - }); diff --git a/doc/2/core-classes/security/search-users/index.md b/doc/2/core-classes/security/search-users/index.md deleted file mode 100644 index 146d9e77..00000000 --- a/doc/2/core-classes/security/search-users/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -code: true -type: page -title: searchUsers -description: Security:searchUsers ---- - -# searchUsers - -Return users matching the given filter. - ---- - -## searchUsers(filters, [options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------- | -| `filters` | JSON Object | Filter in [Elasticsearch's Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/query-filter-context.html) format | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `from` | number | Starting offset | `0` | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `scroll` | string | Start a scroll session, with a time to live equals to this parameter's value following the [Elastisearch time format](https://www.elastic.co/guide/en/elasticsearch/reference/5.0/common-options.html#time-units) | `undefined` | -| `size` | number |  Number of hits to return per result page | `10` | - -:::info -To get more information about scroll sessions, please refer to the [API reference documentation](/core/1/api/controllers/document/search). -::: - ---- - -## Callback Response - -Return a JSON Object - -## Usage - -<<< ./snippets/search-users-1.java - -> Callback response: - -```json -{ - "total": 124, - "users": [ - // array of User objects - ], - // only if a scroll parameter has been provided - "scrollId": "" -} -``` diff --git a/doc/2/core-classes/security/search-users/snippets/search-users-1.java b/doc/2/core-classes/security/search-users/snippets/search-users-1.java deleted file mode 100644 index 8acf4610..00000000 --- a/doc/2/core-classes/security/search-users/snippets/search-users-1.java +++ /dev/null @@ -1,49 +0,0 @@ - -JSONObject filter = new JSONObject() - .put("bool", new JSONObject() - .put("must", new JSONArray() - .put(new JSONObject() - .put("terms", new JSONObject() - .put("profileIds", new JSONArray().put("anonymous").put("default")) - ) - ) - .put(new JSONObject() - .put("geoDistance", new JSONObject() - .put("distance", "10km") - .put("pos", new JSONObject() - .put("lat", 48.8566140) - .put("lon", 2.352222) - ) - ) - ) - ) - ); - -// optional: result pagination configuration -Options options = new Options(); -options.setFrom((long) 0); -options.setSize((long) 42); -options.setScroll("1m"); - -kuzzle - .security - .searchUsers(filters, options, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList users) { - // users.getDocuments() returns an users list - for(User user : users.getDocuments()) { - - } - - // Total number of profiles, regardless of pagination - long total = users.getTotal(); - - // Available only if a "scroll" option has been provided - String scrollId = users.getScroll() - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/update-credentials/index.md b/doc/2/core-classes/security/update-credentials/index.md deleted file mode 100644 index 3a973497..00000000 --- a/doc/2/core-classes/security/update-credentials/index.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -code: true -type: page -title: updateCredentials -description: Security:updateCredentials ---- - -# updateCredentials - -Update the current user's credentials for the specified ``. The credentials to send depend on the authentication plugin and the strategy. - ---- - -## updateCredentials(strategy, kuid, credentials, [options], [callback]) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------ | -| `strategy` | string | Strategy you want to create credentials in | -| `kuid` | JSON object | User's kuid | -| `credentials` | JSON object | The credentials | -| `options` | JSON object | Optional parameters | -| `callback` | function | Optional callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an object with the updated credentials. - -## Usage - -<<< ./snippets/update-credentials-1.java - -> Callback response - -```json -{ - "username": "foo", - "kuid": "" -} -``` diff --git a/doc/2/core-classes/security/update-credentials/snippets/update-credentials-1.java b/doc/2/core-classes/security/update-credentials/snippets/update-credentials-1.java deleted file mode 100644 index 22c9c3e4..00000000 --- a/doc/2/core-classes/security/update-credentials/snippets/update-credentials-1.java +++ /dev/null @@ -1,13 +0,0 @@ - -JSONObject credentials = new JSONObject().put("username", "foo"); - -kuzzle.security.updateCredentials("local", "kuid", credentials, new ResponseListener() { - @Override - public void onSuccess(JSONObject updatedCredentials) { - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/security/update-profile/index.md b/doc/2/core-classes/security/update-profile/index.md deleted file mode 100644 index a7d46749..00000000 --- a/doc/2/core-classes/security/update-profile/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: updateProfile -description: Security:updateProfile ---- - -# updateProfile - -Performs a partial update on an existing profile. - ---- - -## updateProfile(id, content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ---------------- | ----------------------------------------- | -| `id` | string | Unique role identifier | -| `policies` | array of objects | List of policies to apply to this profile | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Security` object to allow chaining. - ---- - -## Callback Response - -Return an updated [Profile](/sdk/java/2/core-classes/profile) object. - -## Usage - -<<< ./snippets/update-profile-1.java diff --git a/doc/2/core-classes/security/update-profile/snippets/update-profile-1.java b/doc/2/core-classes/security/update-profile/snippets/update-profile-1.java deleted file mode 100644 index 54da81da..00000000 --- a/doc/2/core-classes/security/update-profile/snippets/update-profile-1.java +++ /dev/null @@ -1,27 +0,0 @@ - -JSONObject[] policies = new JSONObject[]{ - new JSONObject().put("roleId", "myrole"), - new JSONObject() - .put("roleId", "default") - .put("restrictedTo", new JSONArray() - .put(new JSONObject().put("index", "index1")) - .put(new JSONObject() - .put("index", "index2") - .put("collections", new JSONArray().put("foo").put("bar")) - ) - ) -}; - -kuzzle - .security - .updateProfile("profile ID", policies, new ResponseListener() { - @Override - public void onSuccess(Profile profile) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/update-role/index.md b/doc/2/core-classes/security/update-role/index.md deleted file mode 100644 index ac73bdf9..00000000 --- a/doc/2/core-classes/security/update-role/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: updateRole -description: Security:updateRole ---- - -# updateRole - -Performs a partial update on an existing role. - ---- - -## updateRole(id, content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `id` | string | Unique role identifier | -| `content` | JSON Object | A plain JSON object representing the role | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Security` object to allow chaining. - ---- - -## Callback Response - -Returns an updated [Role](/sdk/java/2/core-classes/role) object. - -## Usage - -<<< ./snippets/update-role-1.java diff --git a/doc/2/core-classes/security/update-role/snippets/update-role-1.java b/doc/2/core-classes/security/update-role/snippets/update-role-1.java deleted file mode 100644 index 17b12ebb..00000000 --- a/doc/2/core-classes/security/update-role/snippets/update-role-1.java +++ /dev/null @@ -1,24 +0,0 @@ - -JSONObject roleDefinition = new JSONObject() - .put("controllers", new JSONObject() - .put("*", new JSONObject() - .put("actions", new JSONObject() - .put("*", true) - ) - ) - ) -); - -kuzzle - .security - .updateRole("Role ID", roleDefinition, new ResponseListener() { - @Override - public void onSuccess(Role role) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/update-user/index.md b/doc/2/core-classes/security/update-user/index.md deleted file mode 100644 index 7b1b305f..00000000 --- a/doc/2/core-classes/security/update-user/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -code: true -type: page -title: updateUser -description: Security:updateUser ---- - -# updateUser - -Performs a partial update on an existing user. - ---- - -## updateUser(id, content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `id` | string | Unique user identifier | -| `content` | JSON Object | A plain JSON object representing the user | -| `options` | string | (Optional) Optional arguments | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Filter | Type | Description | Default | -| ---------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| `queuable` | boolean | Make this request queuable or not | `true` | -| `refresh` | string | If set to `wait_for`, Kuzzle will wait for the persistence layer to finish indexing (available with Elasticsearch 5.x and above) | `undefined` | - ---- - -## Return Value - -Returns the `Security` object to allow chaining. - ---- - -## Callback Response - -Returns an updated [User](/sdk/java/2/core-classes/user) object. - -## Usage - -<<< ./snippets/update-user-1.java diff --git a/doc/2/core-classes/security/update-user/snippets/update-user-1.java b/doc/2/core-classes/security/update-user/snippets/update-user-1.java deleted file mode 100644 index a922b597..00000000 --- a/doc/2/core-classes/security/update-user/snippets/update-user-1.java +++ /dev/null @@ -1,18 +0,0 @@ - -JSONObject newContent = new JSONObject() - .put("firstname", "My Name Is") - .put("lastname", "Jonas"); - -kuzzle - .security - .updateUser("User ID", newContent, new ResponseListener() { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); diff --git a/doc/2/core-classes/security/user/index.md b/doc/2/core-classes/security/user/index.md deleted file mode 100644 index ae20fb8b..00000000 --- a/doc/2/core-classes/security/user/index.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -code: true -type: page -title: user -description: Security:user ---- - -# user - -Instantiates a new [User](/sdk/java/2/core-classes/user) object. - ---- - -## user(id, content) - -| Arguments | Type | Description | -| --------- | ----------- | ---------------------- | -| `id` | string | Unique user identifier | -| `content` | JSON Object | User content | - ---- - -## Return value - -Returns the new [User](/sdk/java/2/core-classes/user) object. - -## Usage - -<<< ./snippets/user-1.java diff --git a/doc/2/core-classes/security/user/snippets/user-1.java b/doc/2/core-classes/security/user/snippets/user-1.java deleted file mode 100644 index f6b966e4..00000000 --- a/doc/2/core-classes/security/user/snippets/user-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -JSONObject userContent = new JSONObject() - // A "profileIds" field is required to bind a user to an existing profile - .put("profileIds", new JSONArray().put('someProfile')) - // The "local" authentication strategy requires a password - .put("password", "a password") - // You can also set custom fields to your user - .put("firstname", "John") - .put("lastname", "Doe"); - -User user = kuzzle.security.user("", userContent); diff --git a/doc/2/core-classes/security/validate-credentials/index.md b/doc/2/core-classes/security/validate-credentials/index.md deleted file mode 100644 index 98b8a83e..00000000 --- a/doc/2/core-classes/security/validate-credentials/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -code: true -type: page -title: validateCredentials -description: Security:validateCredentials ---- - -# validateCredentials - -> - -Validate credentials of user with `kuid` for the specified `strategy`. Resolves to an error if the credentials are invalid. - ---- - -## validateCredentials(strategy, credentials, [options], callback) - -| Arguments | Type | Description | -| ------------- | ----------- | ------------------------------------------ | -| `strategy` | string | Strategy you want to create credentials in | -| `kuid` | JSON object | User's kuid | -| `credentials` | JSON object | The credentials | -| `options` | JSON object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a boolean value if the credentials are valid, otherwise returns an error. - -## Usage - -<<< ./snippets/validate-credentials-1.java - -> Callback response - -```json -true -``` diff --git a/doc/2/core-classes/security/validate-credentials/snippets/validate-credentials-1.java b/doc/2/core-classes/security/validate-credentials/snippets/validate-credentials-1.java deleted file mode 100644 index 10d0c439..00000000 --- a/doc/2/core-classes/security/validate-credentials/snippets/validate-credentials-1.java +++ /dev/null @@ -1,14 +0,0 @@ - -JSONObject credentials = new JSONObject().put("username", "bar"); - -kuzzle.security.validateCredentials("local", "kuid", credentials, new ResponseListener() { - @Override - public void onSuccess(Boolean result) { - - } - - @Override - public void onError(JSONObject error) { - // Handle error - } -} diff --git a/doc/2/core-classes/user/add-profile/index.md b/doc/2/core-classes/user/add-profile/index.md deleted file mode 100644 index dc46fdce..00000000 --- a/doc/2/core-classes/user/add-profile/index.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -code: true -type: page -title: addProfile -description: User:addProfile ---- - -# addProfile - -Replaces the security profile associated with the user. - -:::info -Updating a user will have no impact until the [create](/sdk/java/2/core-classes/user/create) or [replace](/sdk/java/2/core-classes/user/replace) method is called -::: - ---- - -## addProfile(profileId) - -| Arguments | Type | Description | -| ----------- | ------ | ----------- | -| `profileId` | string | Profile ID | - ---- - -## addProfile(profile) - -| Arguments | Type | Description | -| --------- | ------- | --------------------------------------------------------------------- | -| `profile` | Profile | An instantiated [Profile](/sdk/java/2/core-classes/profile) object | - ---- - -## Return Value - -Returns the `User` object. - -## Usage - -<<< ./snippets/add-profile-1.java diff --git a/doc/2/core-classes/user/add-profile/snippets/add-profile-1.java b/doc/2/core-classes/user/add-profile/snippets/add-profile-1.java deleted file mode 100644 index c762ec18..00000000 --- a/doc/2/core-classes/user/add-profile/snippets/add-profile-1.java +++ /dev/null @@ -1,15 +0,0 @@ - - -// Updating the profile with a Profile object -kuzzle - .security - .fetchProfile("myprofile", opts, new ResponseListener() { - @Override - public void onSuccess(Profile profile) { - // Can add the profile directly with a Profile object - user.addProfile(profile); - } - }); - -// Updating the profile with a profile ID -user.addProfile("myprofile"); diff --git a/doc/2/core-classes/user/constructor/index.md b/doc/2/core-classes/user/constructor/index.md deleted file mode 100644 index 615b75d7..00000000 --- a/doc/2/core-classes/user/constructor/index.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -code: true -type: page -title: constructor -description: User:constructor -order: 1 ---- - -# Constructors - -## Instantiates a new User object, which is a representation of a Kuzzle user and is linked to a security [Profile](/sdk/java/2/core-classes/profile). - -## User(Security, id, content, [meta]) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------- | -| `Security` | Security | An instantiated Security object | -| `id` | string | Unique user identifier | -| `content` | JSON Object | User content | -| `meta` | JSON Object | User metadata | - -**Note:** this constructor won't make any call to Kuzzle. - ---- - -## Properties - -| Property name | Type | Description | get/set | -| ------------- | ----------- | ------------------------- | ------- | -| `content` | JSON object | Raw user content | get | -| `id` | string | Unique profile identifier | get | -| `meta` | JSON object | User metadata | get | - ---- - -## Return Value - -Returns the `User` object. - -## Usage - -<<< ./snippets/constructor-1.java diff --git a/doc/2/core-classes/user/constructor/snippets/constructor-1.java b/doc/2/core-classes/user/constructor/snippets/constructor-1.java deleted file mode 100644 index e8b1866e..00000000 --- a/doc/2/core-classes/user/constructor/snippets/constructor-1.java +++ /dev/null @@ -1,15 +0,0 @@ - -JSONObject userContent = new JSONObject() - // A "profile" field is required to bind a user to an existing profile - .put("profileIds", new JSONArray().put("admin")) - // The "local" authentication strategy requires a password - .put("password", "secret password") - // You can also set custom fields to your user - .put("firstname", "John") - .put("lastname", "Doe"); - -// Using the KuzzleSecurity factory: -User user = kuzzle.security.user("user ID", userContent); - -// Or directly with the constructor: -User user = new User(kuzzle.security, "user ID", userContent); diff --git a/doc/2/core-classes/user/create/index.md b/doc/2/core-classes/user/create/index.md deleted file mode 100644 index 5f3d3aec..00000000 --- a/doc/2/core-classes/user/create/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -code: true -type: page -title: create -description: User:create ---- - -# create - -Create the user in Kuzzle. Credentials can be created during the process by using [setCredentials](/sdk/java/2/core-classes/user/set-credentials) beforehand. - ---- - -## create([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `User` object to allow chaining. - ---- - -## Callback Response - -Returns a `User` object. - -## Usage - -<<< ./snippets/create-1.java diff --git a/doc/2/core-classes/user/create/snippets/create-1.java b/doc/2/core-classes/user/create/snippets/create-1.java deleted file mode 100644 index d6f7ae27..00000000 --- a/doc/2/core-classes/user/create/snippets/create-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -user.create(new ResponseListener() { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/user/delete/index.md b/doc/2/core-classes/user/delete/index.md deleted file mode 100644 index e6b7b030..00000000 --- a/doc/2/core-classes/user/delete/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: delete -description: User:delete ---- - -# delete - -Deletes the user in Kuzzle. - ---- - -## delete([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns a `String` containing the id of the deleted user. - -## Usage - -<<< ./snippets/delete-1.java diff --git a/doc/2/core-classes/user/delete/snippets/delete-1.java b/doc/2/core-classes/user/delete/snippets/delete-1.java deleted file mode 100644 index 7386edb3..00000000 --- a/doc/2/core-classes/user/delete/snippets/delete-1.java +++ /dev/null @@ -1,11 +0,0 @@ - -user.delete(new ResponseListener() { - @Override - public void onSuccess(String deletedId) { - - } - - @Override public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/user/get-profileids/index.md b/doc/2/core-classes/user/get-profileids/index.md deleted file mode 100644 index 385f2147..00000000 --- a/doc/2/core-classes/user/get-profileids/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -code: true -type: page -title: getProfileids -description: User:getProfileids ---- - -# getProfileIds - -Returns the list of profile identifiers associated with this user. - ---- - -## Return Value - -Returns an array of strings, each a profile identifier associated with this user. - -## Usage - -<<< ./snippets/get-profileids-1.java diff --git a/doc/2/core-classes/user/get-profileids/snippets/get-profileids-1.java b/doc/2/core-classes/user/get-profileids/snippets/get-profileids-1.java deleted file mode 100644 index eed4412b..00000000 --- a/doc/2/core-classes/user/get-profileids/snippets/get-profileids-1.java +++ /dev/null @@ -1,2 +0,0 @@ - -String[] profileIds = user.getProfileIds(); diff --git a/doc/2/core-classes/user/get-profiles/index.md b/doc/2/core-classes/user/get-profiles/index.md deleted file mode 100644 index 43999904..00000000 --- a/doc/2/core-classes/user/get-profiles/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -code: true -type: page -title: getProfiles -description: User:getProfiles ---- - -# getProfiles - -Gets the security [Profile](/sdk/java/2/core-classes/profile) instances linked to the user from Kuzzle's API. - ---- - -## getProfiles([options], callback) - -| Arguments | Type | Description | -| ---------- | ----------- | ------------------------------ | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Callback Response - -Returns an array of security [Profile](/sdk/java/2/core-classes/profile) objects. - -## Usage - -<<< ./snippets/get-profiles-1.java diff --git a/doc/2/core-classes/user/get-profiles/snippets/get-profiles-1.java b/doc/2/core-classes/user/get-profiles/snippets/get-profiles-1.java deleted file mode 100644 index 641a2358..00000000 --- a/doc/2/core-classes/user/get-profiles/snippets/get-profiles-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -user.getProfiles(new ResponseListener() { - @Override - public void onSuccess(Profile[] profiles) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/user/index.md b/doc/2/core-classes/user/index.md deleted file mode 100644 index 5424b319..00000000 --- a/doc/2/core-classes/user/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -code: true -type: branch -title: User -description: User documentation ---- diff --git a/doc/2/core-classes/user/replace/index.md b/doc/2/core-classes/user/replace/index.md deleted file mode 100644 index 1031ed81..00000000 --- a/doc/2/core-classes/user/replace/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -code: true -type: page -title: replace -description: User:replace ---- - -# replace - -Replaces the user in Kuzzle. - ---- - -## replace([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `User` object to allow chaining. - ---- - -## Callback Response - -Returns a `User` object. - -## Usage - -<<< ./snippets/replace-1.java diff --git a/doc/2/core-classes/user/replace/snippets/replace-1.java b/doc/2/core-classes/user/replace/snippets/replace-1.java deleted file mode 100644 index 832d100e..00000000 --- a/doc/2/core-classes/user/replace/snippets/replace-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -user.replace(new ResponseListener() { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/user/save-restricted/index.md b/doc/2/core-classes/user/save-restricted/index.md deleted file mode 100644 index bd877624..00000000 --- a/doc/2/core-classes/user/save-restricted/index.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -code: true -type: page -title: saveRestricted -description: User:saveRestricted ---- - -# saveRestricted - -## Saves this user as restricted in Kuzzle. - -## saveRestricted([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `User` object to allow chaining. - ---- - -## Callback Response - -Returns a `User` object. - -## Usage - -<<< ./snippets/save-restricted-1.java diff --git a/doc/2/core-classes/user/save-restricted/snippets/save-restricted-1.java b/doc/2/core-classes/user/save-restricted/snippets/save-restricted-1.java deleted file mode 100644 index d99efb0a..00000000 --- a/doc/2/core-classes/user/save-restricted/snippets/save-restricted-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -user.saveRestricted(new ResponseListener() { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/user/save/index.md b/doc/2/core-classes/user/save/index.md deleted file mode 100644 index 37fb47b4..00000000 --- a/doc/2/core-classes/user/save/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -code: true -type: page -title: save -description: User:save ---- - -# save - -Creates or replaces this user in Kuzzle. - ---- - -## save([options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | ----------------------------------------- | -| `options` | JSON Object | Optional parameters | -| `callback` | function | (Optional) Callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `User` object to allow chaining. - ---- - -## Callback Response - -Returns a `User` object. - -## Usage - -<<< ./snippets/save-1.java diff --git a/doc/2/core-classes/user/save/snippets/save-1.java b/doc/2/core-classes/user/save/snippets/save-1.java deleted file mode 100644 index 608499ec..00000000 --- a/doc/2/core-classes/user/save/snippets/save-1.java +++ /dev/null @@ -1,12 +0,0 @@ - -user.save(new ResponseListener { - @Override - public void onSuccess(User user) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/core-classes/user/set-content/index.md b/doc/2/core-classes/user/set-content/index.md deleted file mode 100644 index eb6c20e8..00000000 --- a/doc/2/core-classes/user/set-content/index.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -code: true -type: page -title: setContent -description: User:setContent ---- - -# setContent - -Replaces the content of User. - -:::info -Updating a user will have no impact until the [create](/sdk/java/2/core-classes/user/create) or [replace](/sdk/java/2/core-classes/user/replace) method is called. -::: - ---- - -## setContent(data) - -| Arguments | Type | Description | -| --------- | ----------- | ------------ | -| `data` | JSON Object | User content | - ---- - -## Return Value - -Returns the `User` object. - -## Usage - -<<< ./snippets/set-content-1.java diff --git a/doc/2/core-classes/user/set-content/snippets/set-content-1.java b/doc/2/core-classes/user/set-content/snippets/set-content-1.java deleted file mode 100644 index fc8875ad..00000000 --- a/doc/2/core-classes/user/set-content/snippets/set-content-1.java +++ /dev/null @@ -1,7 +0,0 @@ - -JSONObject newContent = new JSONObject() - .put("profileIds", new JSONArray() - .put("profileId") - ); - -user.setContent(newContent); diff --git a/doc/2/core-classes/user/set-credentials/index.md b/doc/2/core-classes/user/set-credentials/index.md deleted file mode 100644 index ab6591ca..00000000 --- a/doc/2/core-classes/user/set-credentials/index.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -code: true -type: page -title: setCredentials -description: User:setCredentials ---- - -# setCredentials - -Sets the user's credentials. - -:::info -Updating user credentials will have no impact until the [create](/sdk/java/2/core-classes/user/create) method is called. -The credentials to send depend on the authentication plugin and the strategy you want to create credentials for. -::: - ---- - -## setCredentials(credentials) - -| Arguments | Type | Description | -| ------------- | ------ | --------------------------------------------------------------------------------- | -| `credentials` | object | An object containing an attribute for each strategy you want to link the user to. | - ---- - -## Return Value - -Returns the `User` object. - -## Usage - -<<< ./snippets/set-credentials-1.java diff --git a/doc/2/core-classes/user/set-credentials/snippets/set-credentials-1.java b/doc/2/core-classes/user/set-credentials/snippets/set-credentials-1.java deleted file mode 100644 index 287a00c0..00000000 --- a/doc/2/core-classes/user/set-credentials/snippets/set-credentials-1.java +++ /dev/null @@ -1,6 +0,0 @@ - -JSONObject - strategyCredentials = new JSONObject().put("some", "credentials"), - credentials = new JSONObject().put("", strategyCredentials); - -user.setCredentials(credentials); diff --git a/doc/2/core-classes/user/set-profiles/index.md b/doc/2/core-classes/user/set-profiles/index.md deleted file mode 100644 index 92c4855f..00000000 --- a/doc/2/core-classes/user/set-profiles/index.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -code: true -type: page -title: setProfiles -description: User:setProfiles ---- - -# setProfiles - -Replaces the security profiles linked to the user. - -:::info -Updating a user will have no impact until the [create](/sdk/java/2/core-classes/user/create) or [replace](/sdk/java/2/core-classes/user/replace) method is called. -::: - ---- - -## setProfiles(profileIds) - -| Arguments | Type | Description | -| ------------ | ---------------- | ------------------- | -| `profileIds` | array of strings | List of profile IDs | - ---- - -## setProfiles(profiles) - -| Arguments | Type | Description | -| ---------- | ------------------------ | ------------------------------------------------------------------------------- | -| `profiles` | array of Profile objects | An array of instantiated [Profile](/sdk/java/2/core-classes/profile) objects | - ---- - -## Return Value - -Returns the `User` object. - -## Usage - -<<< ./snippets/set-profiles-1.java diff --git a/doc/2/core-classes/user/set-profiles/snippets/set-profiles-1.java b/doc/2/core-classes/user/set-profiles/snippets/set-profiles-1.java deleted file mode 100644 index ac5ef05e..00000000 --- a/doc/2/core-classes/user/set-profiles/snippets/set-profiles-1.java +++ /dev/null @@ -1,22 +0,0 @@ - - -// Updating the profile with a Profile object -kuzzle - .security - .fetchProfile("myprofile", opts, new ResponseListener() { - @Override - public void onSuccess(Profile profile) { - - ArrayList profileIds = new ArrayList(); - profileIds.add(profile); - - user.setProfiles(profileIds); - - } - }); - -// Updating the profile with a profile ID -ArrayList profileIds = new ArrayList(); -profileIds.add("myprofile"); - -user.setProfiles(profileIds); diff --git a/doc/2/core-classes/user/update/index.md b/doc/2/core-classes/user/update/index.md deleted file mode 100644 index ae46a54e..00000000 --- a/doc/2/core-classes/user/update/index.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -code: true -type: page -title: update -description: User:update ---- - -# update - -Performs a partial content update on this object. - ---- - -## update(content, [options], [callback]) - -| Arguments | Type | Description | -| ---------- | ----------- | --------------------------------------- | -| `content` | JSON Object | User content | -| `options` | JSON Object | Optional parameters | -| `callback` | function | Optional callback handling the response | - ---- - -## Options - -| Option | Type | Description | Default | -| ---------- | ------- | --------------------------------- | ------- | -| `queuable` | boolean | Make this request queuable or not | `true` | - ---- - -## Return Value - -Returns the `User` object to allow chaining. - ---- - -## Callback Response - -Returns the updated version of this object. - -## Usage - -<<< ./snippets/update-1.java diff --git a/doc/2/core-classes/user/update/snippets/update-1.java b/doc/2/core-classes/user/update/snippets/update-1.java deleted file mode 100644 index 3f3332f4..00000000 --- a/doc/2/core-classes/user/update/snippets/update-1.java +++ /dev/null @@ -1,16 +0,0 @@ - -JSONObject updateContent = new JSONObject() - .put("firstname", "My Name Is") - .put("lastname", "Jonas"); - -user.update(updateContent, new ResponseListener() { - @Override - public void onSuccess(User updatedUser) { - - } - - @Override - public void onError(JSONObject error) { - - } -}); diff --git a/doc/2/essentials/error-handling/index.md b/doc/2/essentials/error-handling/index.md deleted file mode 100644 index 074f4f64..00000000 --- a/doc/2/essentials/error-handling/index.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -code: false -type: page -title: Error Handling -order: 100 ---- - -# Error Handling - -<<< ./snippets/handling-errors-1.java -All methods that accept a callback as an argument can return an error. The error can be generated directly by the SDK, or by Kuzzle and included in the response to a request. - -All errors generated by Kuzzle contain the following properties: - -- `message`: the error message -- `status`: an error code following the [HTTP standard](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) diff --git a/doc/2/essentials/error-handling/snippets/handling-errors-1.java b/doc/2/essentials/error-handling/snippets/handling-errors-1.java deleted file mode 100644 index 01d121cd..00000000 --- a/doc/2/essentials/error-handling/snippets/handling-errors-1.java +++ /dev/null @@ -1,17 +0,0 @@ - -kuzzle.checkToken("some jwt token", new ResponseListener() { - @Override - public void onSuccess(TokenValidity tokenInfo) { - if (tokenInfo.isValid()) { - // tokenInfo.getExpiresAt() returns the expiration timestamp - } - else { - // tokenInfo.getState() returns the invalidity reason - } - } - - @Override - public void onError(JSONObject error) { - System.err.println(error.getInt('status') + ': ' + error.getString('message')); - } -}); diff --git a/doc/2/essentials/events/index.md b/doc/2/essentials/events/index.md deleted file mode 100644 index 819d2700..00000000 --- a/doc/2/essentials/events/index.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -code: false -type: page -title: Events -order: 200 ---- - -# Events - -The [Kuzzle instance](/sdk/java/2/core-classes/kuzzle) periodically emits named events that provide useful updates about the state of the Kuzzle client. To subscribe to these events, use the [addListener](/sdk/java/2/core-classes/kuzzle/add-listener) function and specify the event name and the callback function that will be executed when the event is emitted. To unsubscribe to an event, use the [removeListener](/sdk/java/2/core-classes/kuzzle/remove-listener) function, specifying the name of the event to remove. - ---- - -## Emitted Events - -| Event Name | Callback arguments | Description | -| ------------------ | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | -| `connected` | _(none)_ | Triggered when the SDK has successfully connected to Kuzzle | -| `discarded` | `error` (object) | Triggered when Kuzzle rejects a request (e.g. request can't be parsed, request too large, ...) | -| `disconnected` | _(none)_ | Triggered when the current session has been unexpectedly disconnected | -| `loginAttempt` | `{ "success": , "error": "" }` | Triggered when a login attempt completes, either with a success or a failure result | -| `networkError` | `error` (object) | Triggered when the SDK has failed to connect to Kuzzle. Does not trigger offline mode. | -| `offlineQueuePop` | `query` (object) | Triggered whenever a request is removed from the offline queue. | -| `offlineQueuePush` | `{ "query": , "cb": }` | Triggered whenever a request is added to the offline queue | -| `queryError` | `error` (object), `query` (object) | Triggered whenever Kuzzle responds with an error | -| `reconnected` | _(none)_ | Triggered when the current session has reconnected to Kuzzle after a disconnection, and only if `autoReconnect` is set to `true` | -| `tokenExpired` | _(none)_ | Triggered when Kuzzle rejected a request because the authentication token expired | - -**Note:** listeners are called in the order of their insertion. diff --git a/doc/2/essentials/index.md b/doc/2/essentials/index.md deleted file mode 100644 index a75e1c5c..00000000 --- a/doc/2/essentials/index.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -code: false -type: branch -order: 0 -title: Essentials -description: Essentials ---- diff --git a/doc/2/essentials/offline-tools/index.md b/doc/2/essentials/offline-tools/index.md deleted file mode 100644 index 2b8b1399..00000000 --- a/doc/2/essentials/offline-tools/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -code: false -type: page -title: Offline Tools -order: 300 ---- - -# Offline Tools - -When using an unstable network connection, an application must maintain a normal behavior when it is disconnected. Our goal is to provide the right toolkit to handle such situations. - ---- - -## Handling a Network Disconnect - -There are two ways to handle a network disconnect: - -- Automatically reconnect to Kuzzle when possible, and enter _offline mode_ in the meantime. This is the default behavior. -- Stop all further communication with Kuzzle and invalidate the current instance and all its children. The application will have to manually reconnect once the network is available. To do so, simply set the `autoReconnect` option to `false` when creating the SDK instance. - -_Offline mode_ refers to the time between a `disconnected` and a `reconnected` event (see [Events](/sdk/java/2/essentials/events)). - ---- - -## Subscriptions - -A subscription opens a permanent pipe between the client and Kuzzle. Whenever a real-time message or a modified document matches a subscription filter, a notification is sent by Kuzzle to the client (for instance, see the [Collection.subscribe](/sdk/java/2/core-classes/collection/subscribe) method). - -While in offline mode, the Kuzzle SDK client maintains all subscriptions configurations and, by default, when Kuzzle SDK client reconnects, all subscriptions are renewed. This behavior can be changed by setting the `autoResubscribe` to `false`, in which case, each subscription will have to be renewed manually using the `Room.renew` method. - ---- - -## API Requests - -While in offline mode, API requests can be queued, and then executed once the network connection has been reestablished. -By default, there is no request queuing. - -- Queue all requests automatically when going offline by setting the `autoQueue` option to `true` (see [Kuzzle SDK constructor](/sdk/java/2/core-classes/kuzzle)) -- Start and stop queuing manually, by using the [startQueuing](/sdk/java/2/core-classes/kuzzle/start-queuing) and [stopQueuing](/sdk/java/2/core-classes/kuzzle/stop-queuing) methods - -The queue itself can be configured using the `queueTTL` and `queueMaxSize` options. - ---- - -## Filtering Requests to be Queued - -By default, when queuing is first activated, all requests are queued. - -However, you can choose to omit certain request by using the [`queueFilter`](/sdk/java/2/core-classes/kuzzle#properties) property. This property can be set to a function that accepts the request as an input value and returns a boolean result which indicates whether or not the request should be queud. - -Additionally, almost all request methods accept a `queuable` option, which when set to `false`, will cause the request to be discarded if the Kuzzle SDK is disconnected. This option overrides the `queueFilter` property. - ---- - -## Handling Network Reconnect - - - -Once a `reconnected` event is fired, you may replay the content of the queue with the `playQueue` method. Or you can let the Kuzzle SDK replay it automatically upon reconnection by setting the `autoReplay` option to `true`. - -Requests are sent to Kuzzle with a `replayInterval` delay between each call. - -Any request made while the client is processing the queue will be delayed until the queue is empty. This ensures that all requests are played in the right order. - ---- - -## Taking Control of the Offline Queue - -You can be notified about what's going on in the offline queue, by using the [`offlineQueuePush`](/sdk/java/2/essentials/events) and the [`offlineQueuePop`](/sdk/java/2/essentials/events) events. - -The `offlineQueuePush` event is fired whenever a request is queued. It will emit an object containing a `query` property, describing the queued request, and an optional `cb` property containing the corresponding callback, if any. - -The `offlineQueuePop` event is fired whenever a request has been removed from the queue, either because the queue limits have been reached, or because the request has been replayed. It provides the removed request to its listeners. - -The `offlineQueueLoader` property of the Kuzzle SDK instance loads requests to the queue, **before any previously queued request**. It is invoked every time the Kuzzle SDK starts dequeuing requests. -This property must be set with a function that returns an array of objects with the following accessible properties: - -- a `query` property, containing the request to be replayed -- an optional `cb` property pointing to the callback to invoke after the completion of the request - -Finally, if the provided methods don't give you enough control over the offline queue, you can access and edit the queue directly using the `offlineQueue` property. - ---- - -## Automatic Offline-Mode - -You can set the `offlineMode` option to `auto` when instantiating the [Kuzzle SDK instance](/sdk/java/2/core-classes/kuzzle). This sets the offline mode configuration to the following presets: - -- `autoReconnect` = `true` -- `autoQueue` = `true` -- `autoReplay` = `true` -- `autoResubscribe` = `true` diff --git a/doc/2/essentials/realtime-notifications/index.md b/doc/2/essentials/realtime-notifications/index.md deleted file mode 100644 index 4c88f410..00000000 --- a/doc/2/essentials/realtime-notifications/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -code: false -type: page -title: Realtime Notifications -order: 300 ---- - -# Realtime Notifications - -With Kuzzle, you don't [subscribe](/sdk/java/2/core-classes/collection/subscribe) to a room or a topic but, instead, you subscribe to documents. -This means, that when you want to subscribe you must provide a set of filter definitions, using [Koncorde](/core/1/guides/cookbooks/realtime-api), that tell Kuzzle what documents should trigger a notification. Then, any time a document matches the defined filters, Kuzzle will send a notification to the subscriber. - -You can also provide an empty set of filters, which will tell Kuzzle that you want to listen to any change occurring on a collection, emulating the behavior of a traditional topic. - -To subscribe, you must provide a callback that will be called each time a new notification is received. - -Once you have subscribed, depending on the subscription configuration you provided, you may receive a notification when: - -- a pub/sub message matches your criteria (real-time) -- a matching document is about to be created or deleted in real-time (deactivated by default) -- a matching document is created, updated or deleted (once the change is effective in the database) -- a user enters or leaves the room (deactivated by default) - -You may subscribe multiple times to the same room, with identical or different subscription parameters, and with different callbacks. This allows you to dispatch notifications to dedicated processes of your application, instead of maintaining a single all-purpose notification consumer (but you can do that too I you want). - ---- - -## Document Notification - -| Notification field | Type | Description | Possible values | -| ------------------ | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | ----------------- | -| `document` | [Document](/sdk/java/2/core-classes/document) | Content of the document or real-time message that generated the notification | | -| `scope` | string | Indicates if the document enters or exits the subscription scope | `in`, `out` | -| `state` | string | Shows if the document is about to be changed, or if the change is done | `pending`, `done` | -| `type` | string | Notification type | `document` | - -#### Example - -```json -{ - "status": 200, - "requestId": "bc41ced6-38fc-42b9-8fd5-22ae0774aac2", - "controller": "name of the controller that generated the notification", - "action": "name of the action that generated the notification", - "collection": "collection name", - "index": "index name", - "volatile": {}, - "state": "done", - "scope": "in", - "type": "document", - "document": { - "content": { - "content": "document content example" - }, - "id": "" - } -} -``` - ---- - -## User notification - -| Notification field | Type | Description | Possible values | -| ------------------ | ----------- | -------------------------------------------------------------------------- | --------------- | -| `user` | string | Indicates if the user enters or leaves the subscribed room | `in`, `out` | -| `volatile` | JSON object | If provided during subscription, contains application specific information | | -| `result.count` | integer | Updated number of users subscribing to this room | | -| `type` | string | Notification type | `user` | - -#### Example - -```json -{ - "status": 200, - "roomId": "ID of the room concerned by this notification", - "requestId": "5897cd2f-a8a2-40b2-aa43-b31898172008", - "controller": "subscribe", - "user": "in", - "protocol": "protocol used by the notifying user", - "timestamp": 1453193069592, - "volatile": { - "optional": "user information" - }, - "type": "user", - "result": { - "count": 42 - } -} -``` diff --git a/doc/2/index.md b/doc/2/index.md deleted file mode 100644 index 002542d1..00000000 --- a/doc/2/index.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -code: false -type: root -order: 6 -title: JAVA SDK 2.x -description: JAVA SDK v2.x ---- diff --git a/doc/2/.vuepress b/doc/3/.vuepress similarity index 100% rename from doc/2/.vuepress rename to doc/3/.vuepress diff --git a/doc/3/controllers/auth/check-token/index.md b/doc/3/controllers/auth/check-token/index.md new file mode 100644 index 00000000..12b24375 --- /dev/null +++ b/doc/3/controllers/auth/check-token/index.md @@ -0,0 +1,35 @@ +--- +code: true +type: page +title: CheckToken +description: Checks an authentication Token's validity. +--- + +# CheckToken + +Checks an authentication token's validity. + +## Arguments + +```java +public CompletableFuture> checkToken(final String token) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|----------|-------------------|-------------| +| `token` |
String
| Authentication token | + +## Return + +A ConcurrentHashMap which has the following properties: + +| Property | Type | Description | +|--------------|-------------------|----------------------------------| +| `valid` |
boolean
| Token validity | +| `state` |
String
| Explain why the token is invalid | +| `expires_at` |
int
| Token expiration timestamp | + +## Usage + +<<< ./snippets/check-token.java \ No newline at end of file diff --git a/doc/3/controllers/auth/check-token/snippets/check-token.java b/doc/3/controllers/auth/check-token/snippets/check-token.java new file mode 100644 index 00000000..3ec31bb2 --- /dev/null +++ b/doc/3/controllers/auth/check-token/snippets/check-token.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +ConcurrentHashMap response = kuzzle.getAuthController().login("local", credentials).get(); +ConcurrentHashMap responseToken = kuzzle.getAuthController().checkToken(response.get("jwt").toString()).get(); diff --git a/doc/3/controllers/auth/check-token/snippets/check-token.test.yml b/doc/3/controllers/auth/check-token/snippets/check-token.test.yml new file mode 100644 index 00000000..7ed24530 --- /dev/null +++ b/doc/3/controllers/auth/check-token/snippets/check-token.test.yml @@ -0,0 +1,7 @@ +name: Auth#CheckToken +description: Checks an authentication token's validity. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/auth/create-my-credentials/index.md b/doc/3/controllers/auth/create-my-credentials/index.md new file mode 100644 index 00000000..0e11aaec --- /dev/null +++ b/doc/3/controllers/auth/create-my-credentials/index.md @@ -0,0 +1,31 @@ +--- +code: true +type: page +title: CreateMyCredentials +description: Create the current user's credentials for the specified strategy. +--- + +# CreateMyCredentials + +Creates the current user's credentials for the specified strategy. + +## Arguments + +```java +public CompletableFuture> createMyCredentials(final String strategy, + final ConcurrentHashMap credentials) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|---------------|--------------------|--------------------------------------| +| `strategy` |
String
| Strategy to use | +| `credentials` |
ConcurrentHashMap
| ConcurrentHashMap representing the credentials | + +## Return + +A ConcurrentHashMap representing the new credentials. + +## Usage + +<<< ./snippets/create-my-credentials.java diff --git a/doc/3/controllers/auth/create-my-credentials/snippets/create-my-credentials.java b/doc/3/controllers/auth/create-my-credentials/snippets/create-my-credentials.java new file mode 100644 index 00000000..04c80a31 --- /dev/null +++ b/doc/3/controllers/auth/create-my-credentials/snippets/create-my-credentials.java @@ -0,0 +1,11 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +ConcurrentHashMap newCredentials = new ConcurrentHashMap<>(); +newCredentials.put("username", "foo2"); +newCredentials.put("password", "bar2"); + +ConcurrentHashMap response = + kuzzle.getAuthController().login("local", credentials).get(); +kuzzle.getAuthController().createMyCredentials("other", newCredentials).get(); diff --git a/doc/3/controllers/auth/create-my-credentials/snippets/create-my-credentials.test.yml b/doc/3/controllers/auth/create-my-credentials/snippets/create-my-credentials.test.yml new file mode 100644 index 00000000..5fddc144 --- /dev/null +++ b/doc/3/controllers/auth/create-my-credentials/snippets/create-my-credentials.test.yml @@ -0,0 +1,7 @@ +name: Auth#CreateMyCredentials +description: Creates the current user's credentials for the specified strategy. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: catch +expected: io.kuzzle.sdk.Exceptions.ApiErrorException:\ Unknown\ authentication\ strategy\ "other" diff --git a/doc/3/controllers/auth/credentials-exist/index.md b/doc/3/controllers/auth/credentials-exist/index.md new file mode 100644 index 00000000..9d1e406a --- /dev/null +++ b/doc/3/controllers/auth/credentials-exist/index.md @@ -0,0 +1,29 @@ +--- +code: true +type: page +title: CredentialsExist +description: Checks that the current user has credentials for the specified strategy. +--- + +# CredentialsExist + +Checks that the current user has credentials for the specified strategy. + +## Arguments + +```java +public CompletableFuture credentialsExist(final String strategy) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|------------|-------------------|-----------------| +| `strategy` |
String
| Strategy to use | + +## Return + +A boolean indicating if credentials exist for the strategy. + +## Usage + +<<< ./snippets/credentials-exist.java diff --git a/doc/3/controllers/auth/credentials-exist/snippets/credentials-exist.java b/doc/3/controllers/auth/credentials-exist/snippets/credentials-exist.java new file mode 100644 index 00000000..2b30c7a6 --- /dev/null +++ b/doc/3/controllers/auth/credentials-exist/snippets/credentials-exist.java @@ -0,0 +1,9 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +Boolean exists = kuzzle.getAuthController().credentialsExist("local").get(); +if (exists) { + System.out.println("Credentials exists for local strategy"); +} diff --git a/doc/3/controllers/auth/credentials-exist/snippets/credentials-exist.test.yml b/doc/3/controllers/auth/credentials-exist/snippets/credentials-exist.test.yml new file mode 100644 index 00000000..2f519b43 --- /dev/null +++ b/doc/3/controllers/auth/credentials-exist/snippets/credentials-exist.test.yml @@ -0,0 +1,7 @@ +name: Auth#CredentialsExistAsync +description: Checks that the current user has credentials for the specified strategy. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: default +expected: Credentials\ exists\ for\ local\ strategy diff --git a/doc/3/controllers/auth/delete-my-credentials/index.md b/doc/3/controllers/auth/delete-my-credentials/index.md new file mode 100644 index 00000000..a19ef6df --- /dev/null +++ b/doc/3/controllers/auth/delete-my-credentials/index.md @@ -0,0 +1,25 @@ +--- +code: true +type: page +title: DeleteMyCredentials +description: Deletes the current user's credentials for the specified strategy. +--- + +# DeleteMyCredentials + +Deletes the current user's credentials for the specified strategy. If the credentials that generated the current authentication token are removed, the user will remain logged in until they log out or until their session expires. After that they will no longer be able to log in with the deleted credentials. + +## Arguments + +```java +public CompletableFuture deleteMyCredentials(final String strategy) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|------------|-------------------|-----------------| +| `strategy` |
String
| Strategy to use | + +## Usage + +<<< ./snippets/delete-my-credentials.java diff --git a/doc/3/controllers/auth/delete-my-credentials/snippets/delete-my-credentials.java b/doc/3/controllers/auth/delete-my-credentials/snippets/delete-my-credentials.java new file mode 100644 index 00000000..debdfa83 --- /dev/null +++ b/doc/3/controllers/auth/delete-my-credentials/snippets/delete-my-credentials.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +ConcurrentHashMap response = kuzzle.getAuthController().login("local", credentials).get(); +kuzzle.getAuthController().deleteMyCredentials("local").get(); diff --git a/doc/3/controllers/auth/delete-my-credentials/snippets/delete-my-credentials.test.yml b/doc/3/controllers/auth/delete-my-credentials/snippets/delete-my-credentials.test.yml new file mode 100644 index 00000000..dcc8e528 --- /dev/null +++ b/doc/3/controllers/auth/delete-my-credentials/snippets/delete-my-credentials.test.yml @@ -0,0 +1,7 @@ +name: Auth#DeleteMyCredentialsAsync +description: Deletes the current user's credentials for the specified. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/auth/get-current-user/index.md b/doc/3/controllers/auth/get-current-user/index.md new file mode 100644 index 00000000..46a75ddf --- /dev/null +++ b/doc/3/controllers/auth/get-current-user/index.md @@ -0,0 +1,31 @@ +--- +code: true +type: page +title: GetCurrentUser +description: Returns the profile object for the user linked to the `JSON Web Token`. +--- + +# GetCurrentUserAsync + +Returns informations about the user currently loggued with the SDK instance. + +## Arguments + +```java +public CompletableFuture> getCurrentUser() + throws NotConnectedException, InternalException +``` + +## Return + +A ConcurrentHashMap representing the User. + +| Property | Type | Description | +|--------------|--------------------|---------------------------------------------------| +| `_id` |
String
| Representing the current user `kuid` | +| `strategies` |
Array
| Available authentication strategies for that user | +| `_source` |
ConcurrentHashMap
| User information | + +## Usage + +<<< ./snippets/get-current-user.java diff --git a/doc/3/controllers/auth/get-current-user/snippets/get-current-user.java b/doc/3/controllers/auth/get-current-user/snippets/get-current-user.java new file mode 100644 index 00000000..0ee6ec1e --- /dev/null +++ b/doc/3/controllers/auth/get-current-user/snippets/get-current-user.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +ConcurrentHashMap result = kuzzle.getAuthController().getCurrentUser().get(); diff --git a/doc/3/controllers/auth/get-current-user/snippets/get-current-user.test.yml b/doc/3/controllers/auth/get-current-user/snippets/get-current-user.test.yml new file mode 100644 index 00000000..047325ac --- /dev/null +++ b/doc/3/controllers/auth/get-current-user/snippets/get-current-user.test.yml @@ -0,0 +1,7 @@ +name: Auth#GetCurrentUser +description: Returns the profile object for the user linked to the `JSON Web Token`. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: ^{strategies=\[local\],\ _source={profileIds=\[default\],\ _kuzzle_info={.*}},\ _id=foo}$ diff --git a/doc/3/controllers/auth/get-my-credentials/index.md b/doc/3/controllers/auth/get-my-credentials/index.md new file mode 100644 index 00000000..12dcda4b --- /dev/null +++ b/doc/3/controllers/auth/get-my-credentials/index.md @@ -0,0 +1,29 @@ +--- +code: true +type: page +title: GetMyCredentials +description: Returns the current user's credential information for the specified strategy. +--- + +# GetMyCredentials + +Returns the current user's credential information for the specified strategy. The data returned will depend on the specified strategy. The result can be empty. + +## Arguments + +```java +public CompletableFuture> getMyCredentials() + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|------------|-------------------|-----------------| +| `strategy` |
String
| Strategy to use | + +## Return + +Returns a ConcurrentHashMap representing the credentials for the provided authentication strategy. + +## Usage + +<<< ./snippets/get-my-credentials.java diff --git a/doc/3/controllers/auth/get-my-credentials/snippets/get-my-credentials.java b/doc/3/controllers/auth/get-my-credentials/snippets/get-my-credentials.java new file mode 100644 index 00000000..916cc641 --- /dev/null +++ b/doc/3/controllers/auth/get-my-credentials/snippets/get-my-credentials.java @@ -0,0 +1,7 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +ConcurrentHashMap result = + kuzzle.getAuthController().getMyCredentials("local").get(); diff --git a/doc/3/controllers/auth/get-my-credentials/snippets/get-my-credentials.test.yml b/doc/3/controllers/auth/get-my-credentials/snippets/get-my-credentials.test.yml new file mode 100644 index 00000000..acc13e04 --- /dev/null +++ b/doc/3/controllers/auth/get-my-credentials/snippets/get-my-credentials.test.yml @@ -0,0 +1,8 @@ +name: Auth#GetMyCredentials +description: Returns the current user's credential information for the specified strategy. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: + - {kuid=foo,\ username=foo} diff --git a/doc/3/controllers/auth/get-my-rights/index.md b/doc/3/controllers/auth/get-my-rights/index.md new file mode 100644 index 00000000..50e42c72 --- /dev/null +++ b/doc/3/controllers/auth/get-my-rights/index.md @@ -0,0 +1,25 @@ +--- +code: true +type: page +title: GetMyRights +description: Returns the rights for the user linked to the `JSON Web Token`. +--- + +# GetMyRights + +Returns the rights for the currently logged in user within the SDK instance. + +## Arguments + +```java +public CompletableFuture> getMyRights() + throws NotConnectedException, InternalException +``` + +## Return + +An ArrayList object. + +## Usage + +<<< ./snippets/get-my-rights.java diff --git a/doc/3/controllers/auth/get-my-rights/snippets/get-my-rights.java b/doc/3/controllers/auth/get-my-rights/snippets/get-my-rights.java new file mode 100644 index 00000000..d93e5473 --- /dev/null +++ b/doc/3/controllers/auth/get-my-rights/snippets/get-my-rights.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +ArrayList result = kuzzle.getAuthController().getMyRights().get(); diff --git a/doc/3/controllers/auth/get-my-rights/snippets/get-my-rights.test.yml b/doc/3/controllers/auth/get-my-rights/snippets/get-my-rights.test.yml new file mode 100644 index 00000000..5873e365 --- /dev/null +++ b/doc/3/controllers/auth/get-my-rights/snippets/get-my-rights.test.yml @@ -0,0 +1,7 @@ +name: Auth#GetMyRights +description: Returns the rights for the user linked to the `JSON Web Token`. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: [{controller=*,\ action=*,\ index=*,\ collection=*,\ value=allowed}] diff --git a/doc/3/controllers/auth/get-strategies/index.md b/doc/3/controllers/auth/get-strategies/index.md new file mode 100644 index 00000000..7892d289 --- /dev/null +++ b/doc/3/controllers/auth/get-strategies/index.md @@ -0,0 +1,25 @@ +--- +code: true +type: page +title: GetStrategies +description: Get all authentication strategies registered in Kuzzle. +--- + +# GetStrategies + +Gets all authentication strategies registered in Kuzzle. + +## Arguments + +```java +public CompletableFuture> getStrategies() + throws NotConnectedException, InternalException +``` + +## Return + +An ArrayList representing the available authentication strategies. + +## Usage + +<<< ./snippets/get-strategies.java diff --git a/doc/3/controllers/auth/get-strategies/snippets/get-strategies.java b/doc/3/controllers/auth/get-strategies/snippets/get-strategies.java new file mode 100644 index 00000000..0f19782b --- /dev/null +++ b/doc/3/controllers/auth/get-strategies/snippets/get-strategies.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +ArrayList result = kuzzle.getAuthController().getStrategies().get(); diff --git a/doc/3/controllers/auth/get-strategies/snippets/get-strategies.test.yml b/doc/3/controllers/auth/get-strategies/snippets/get-strategies.test.yml new file mode 100644 index 00000000..e704fb36 --- /dev/null +++ b/doc/3/controllers/auth/get-strategies/snippets/get-strategies.test.yml @@ -0,0 +1,7 @@ +name: Auth#GetStrategies +description: Returns the rights for the user linked to the `JSON Web Token`. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: [local] diff --git a/doc/3/controllers/auth/index.md b/doc/3/controllers/auth/index.md new file mode 100644 index 00000000..6aef4117 --- /dev/null +++ b/doc/3/controllers/auth/index.md @@ -0,0 +1,8 @@ +--- +code: true +type: branch +title: Auth +description: Auth Controller +--- + +# Auth Controller \ No newline at end of file diff --git a/doc/3/controllers/auth/login/index.md b/doc/3/controllers/auth/login/index.md new file mode 100644 index 00000000..e310beed --- /dev/null +++ b/doc/3/controllers/auth/login/index.md @@ -0,0 +1,62 @@ +--- +code: true +type: page +title: Login +description: Authenticates a user. +--- + +# Login + +Authenticates a user. + +If this action is successful, all further requests emitted by this SDK instance will be in the name of the authenticated user, until either the authenticated token expires, the [logout](/sdk/java/3/controllers/auth/logout) action is called, or the authentication token property is manually unset. + +## Arguments + +```java +CompletableFuture> login( + final String strategy, + final ConcurrentHashMap credentials, + final String expiresIn) + throws NotConnectedException, InternalException +``` + +
+ +| Argument | Type | Description | +|---------------|----------------------|--------------------------------------| +| `strategy` |
String
| Strategy to use | +| `credentials` |
ConcurrentHashMap
| Hashmap representing the credentials | +| `expiresIn` |
String
| Token duration | + +#### strategy + +The name of the authentication [strategy](/core/2/guides/kuzzle-depth/authentication/#authentication) used to log the user in. + +Depending on the chosen authentication `strategy`, additional [credential arguments](/core/2/guides/kuzzle-depth/authentication/#authentication) may be required. +The API request example on this page provides the necessary arguments for the [`local` authentication plugin](https://github.com/kuzzleio/kuzzle-plugin-auth-passport-local). + +Check the appropriate [authentication plugin](/core/2/plugins/guides/strategies/overview) documentation to get the list of additional arguments to provide. + + +### expiresIn + +The default value for the `expiresIn` option is defined at server level, in Kuzzle's [configuration file](/core/2/guides/essentials/configuration). + + +## Return + +Returns a Hashmap with the following properties: + +| Property | Type | Description | +|-------------|-------------------|------------------------------------------------------------------------------------------| +| `_id` |
String
| User's `kuid` | +| `jwt` |
String
| Encrypted authentication token, that must then be sent in the requests headers or in the query | +| `expiresAt` |
int
| Token expiration date, in Epoch-millis (UTC) | +| `ttl` |
int
| Token time to live, in milliseconds | + +Once `auth:login` has been called, the returned authentication token is stored by the SDK and used for all the subsequent API call, ensuring they are properly authenticated. + +## Usage + +<<< ./snippets/login.java diff --git a/doc/3/controllers/auth/login/snippets/login.java b/doc/3/controllers/auth/login/snippets/login.java new file mode 100644 index 00000000..7db19af2 --- /dev/null +++ b/doc/3/controllers/auth/login/snippets/login.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); + credentials.put("username", "foo"); + credentials.put("password", "bar"); + +ConcurrentHashMap result = + kuzzle.getAuthController().login("local", credentials).get(); diff --git a/doc/3/controllers/auth/login/snippets/login.test.yml b/doc/3/controllers/auth/login/snippets/login.test.yml new file mode 100644 index 00000000..7e926dcf --- /dev/null +++ b/doc/3/controllers/auth/login/snippets/login.test.yml @@ -0,0 +1,8 @@ +--- +name: Auth#Login +description: Authenticates a user. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: ^{jwt=.*,\ _id=foo,\ ttl=3600000,\ expiresAt=[0-9]+}$ diff --git a/doc/3/controllers/auth/logout/index.md b/doc/3/controllers/auth/logout/index.md new file mode 100644 index 00000000..7d1410d6 --- /dev/null +++ b/doc/3/controllers/auth/logout/index.md @@ -0,0 +1,25 @@ +--- +code: true +type: page +title: Logout +description: Revokes the user's token & unsubscribe them from registered rooms. +--- + +# Logout + +Revokes the user's token & unsubscribes them from registered rooms. + +## Arguments + +```java +public CompletableFuture logout() + throws NotConnectedException, InternalException +``` + +## Return + +A [Response](/sdk/java/3/core-classes/response) object. + +## Usage + +<<< ./snippets/logout.java diff --git a/doc/3/controllers/auth/logout/snippets/logout.java b/doc/3/controllers/auth/logout/snippets/logout.java new file mode 100644 index 00000000..d2a8f8b2 --- /dev/null +++ b/doc/3/controllers/auth/logout/snippets/logout.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +kuzzle.getAuthController().logout(); diff --git a/doc/3/controllers/auth/logout/snippets/logout.test.yml b/doc/3/controllers/auth/logout/snippets/logout.test.yml new file mode 100644 index 00000000..38e8d693 --- /dev/null +++ b/doc/3/controllers/auth/logout/snippets/logout.test.yml @@ -0,0 +1,7 @@ +name: Auth#Logout +description: Revokes the user's token & unsubscribe them from registered rooms. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: default +expected: Success diff --git a/doc/3/controllers/auth/refresh-token/index.md b/doc/3/controllers/auth/refresh-token/index.md new file mode 100644 index 00000000..cd1c8f08 --- /dev/null +++ b/doc/3/controllers/auth/refresh-token/index.md @@ -0,0 +1,43 @@ +--- +code: true +type: page +title: RefreshToken +description: Refreshes an authentication token. +--- + +# RefreshToken + +Refreshes an authentication token. + +- a valid, non-expired authentication must be provided +- the provided authentication token is revoked +- a new authentication token is generated and returned + +## Arguments + +```java +CompletableFuture> refreshToken( + final String expiresIn) throws NotConnectedException, InternalException +``` + +**Optional:** + +| Argument | Type | Description | +|-------------|-------------------|-----------------------------------------------------------------------------| +| `expiresIn` |
String
| Set the token expiration duration (default: depends on Kuzzle configuration file) | + +## Return + +A ConcurrentHashMap with the following properties: + +| Property | Type | Description | +|-------------|-------------------|------------------------------------------------------------------------------------------| +| `_id` |
String
| User's `kuid` | +| `jwt` |
String
| Encrypted authentication token, that must then be sent in the requests headers or in the query | +| `expiresAt` |
int
| Token expiration date, in Epoch-millis (UTC) | +| `ttl` |
int
| Token time to live, in milliseconds | +Once `auth:refreshToken` has been called, the returned authentication token is stored by the SDK and used for all the subsequent API calls. + +## Usage + +<<< ./snippets/refresh-token.java diff --git a/doc/3/controllers/auth/refresh-token/snippets/refresh-token.java b/doc/3/controllers/auth/refresh-token/snippets/refresh-token.java new file mode 100644 index 00000000..4883c424 --- /dev/null +++ b/doc/3/controllers/auth/refresh-token/snippets/refresh-token.java @@ -0,0 +1,7 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +ConcurrentHashMap result = + kuzzle.getAuthController().refreshToken("1h").get(); diff --git a/doc/3/controllers/auth/refresh-token/snippets/refresh-token.test.yml b/doc/3/controllers/auth/refresh-token/snippets/refresh-token.test.yml new file mode 100644 index 00000000..9de330c4 --- /dev/null +++ b/doc/3/controllers/auth/refresh-token/snippets/refresh-token.test.yml @@ -0,0 +1,7 @@ +name: Auth#RefreshToken +description: Refreshes an authentication token. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: ^{jwt=.*,\ _id=foo,\ ttl=3600000,\ expiresAt=[0-9]+}$ diff --git a/doc/3/controllers/auth/update-my-credentials/index.md b/doc/3/controllers/auth/update-my-credentials/index.md new file mode 100644 index 00000000..c7081c11 --- /dev/null +++ b/doc/3/controllers/auth/update-my-credentials/index.md @@ -0,0 +1,37 @@ +--- +code: true +type: page +title: UpdateMyCredentials +description: Updates the current user's credentials for the specified strategy. +--- + +# UpdateMyCredentials + +Updates the current user's credentials for the specified strategy. The credentials to send will depend on the authentication plugin and the authentication strategy. + +## Arguments + +```java +CompletableFuture> updateMyCredentials( + final String strategy, + final ConcurrentHashMap credentials) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|---------------|--------------------|--------------------------------------| +| `strategy` |
String
| Strategy to use | +| `credentials` |
ConcurrentHashMap
| JObject representing the credentials | + +## Return + +A ConcurrentHashMap representing the updated credentials with the following properties: + +| Property | Type | Description | +|------------|-------------------|-------------------| +| `username` |
String
| The Username | +| `kuid` |
String
| The user's `kuid` | + +## Usage + +<<< ./snippets/update-my-credentials.java diff --git a/doc/3/controllers/auth/update-my-credentials/snippets/update-my-credentials.java b/doc/3/controllers/auth/update-my-credentials/snippets/update-my-credentials.java new file mode 100644 index 00000000..73021f4f --- /dev/null +++ b/doc/3/controllers/auth/update-my-credentials/snippets/update-my-credentials.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +ConcurrentHashMap result = kuzzle.getAuthController().updateMyCredentials("local", credentials).get(); diff --git a/doc/3/controllers/auth/update-my-credentials/snippets/update-my-credentials.test.yml b/doc/3/controllers/auth/update-my-credentials/snippets/update-my-credentials.test.yml new file mode 100644 index 00000000..5f6b297f --- /dev/null +++ b/doc/3/controllers/auth/update-my-credentials/snippets/update-my-credentials.test.yml @@ -0,0 +1,7 @@ +name: Auth#UpdateMyCredentials +description: Updates the current user's credentials for the specified strategy. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: {username=foo} diff --git a/doc/3/controllers/auth/update-self/index.md b/doc/3/controllers/auth/update-self/index.md new file mode 100644 index 00000000..a912660f --- /dev/null +++ b/doc/3/controllers/auth/update-self/index.md @@ -0,0 +1,35 @@ +--- +code: true +type: page +title: UpdateSelf +description: Updates the current user object in Kuzzle. +--- + +# UpdateSelf + +Updates the current user object in Kuzzle. + +## Arguments + +```java +CompletableFuture> updateSelf( + final ConcurrentHashMap content) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|-----------|--------------------|---------------------------------------| +| `content` |
ConcurrentHashMap
| Hashmap representing the user content | + +## Return + +Returns a ConcurrentHashMap with the following properties: + +| Property | Type | Description | +|-----------|--------------------|-------------------------------------------| +| `_id` |
String
| User's `kuid` | +| `_source` |
ConcurrentHashMap
| Additional (and optional) user properties | + +## Usage + +<<< ./snippets/update-self.java diff --git a/doc/3/controllers/auth/update-self/snippets/update-self.java b/doc/3/controllers/auth/update-self/snippets/update-self.java new file mode 100644 index 00000000..4d142b15 --- /dev/null +++ b/doc/3/controllers/auth/update-self/snippets/update-self.java @@ -0,0 +1,11 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); + +ConcurrentHashMap custom = new ConcurrentHashMap<>(); +custom.put("age", 42); + +ConcurrentHashMap result = + kuzzle.getAuthController().updateSelf(custom).get(); diff --git a/doc/3/controllers/auth/update-self/snippets/update-self.test.yml b/doc/3/controllers/auth/update-self/snippets/update-self.test.yml new file mode 100644 index 00000000..56a8f326 --- /dev/null +++ b/doc/3/controllers/auth/update-self/snippets/update-self.test.yml @@ -0,0 +1,7 @@ +name: Auth#UpdateSelf +description: Updates the current user object in Kuzzle. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: ^{_source={profileIds=\[default\],\ _kuzzle_info={createdAt=[0-9]+,\ author=-1},\ age=42},\ _id=foo}$ diff --git a/doc/3/controllers/auth/validate-my-credentials/index.md b/doc/3/controllers/auth/validate-my-credentials/index.md new file mode 100644 index 00000000..a56a7f70 --- /dev/null +++ b/doc/3/controllers/auth/validate-my-credentials/index.md @@ -0,0 +1,31 @@ +--- +code: true +type: page +title: ValidateMyCredentials +description: Validates the current user's credentials for the specified strategy. +--- + +# ValidateMyCredentials + +Validates the current user's credentials for the specified strategy. This method returns `true` if the provided credentials are valid; otherwise an error is triggered. This route does not actually create or modify the user credentials. The credentials to send will depend on the authentication plugin and authentication strategy. + +## Arguments + +```java +CompletableFuture validateMyCredentials(final String strategy, + final ConcurrentHashMap credentials) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|---------------|--------------------|--------------------------------------| +| `strategy` |
String
| Strategy to use | +| `credentials` |
ConcurrentHashMap
| A Hashmap representing the credentials | + +## Return + +A boolean indicating if the credentials are valid. + +## Usage + +<<< ./snippets/validate-my-credentials.java diff --git a/doc/3/controllers/auth/validate-my-credentials/snippets/validate-my-credentials.java b/doc/3/controllers/auth/validate-my-credentials/snippets/validate-my-credentials.java new file mode 100644 index 00000000..2888af52 --- /dev/null +++ b/doc/3/controllers/auth/validate-my-credentials/snippets/validate-my-credentials.java @@ -0,0 +1,6 @@ +ConcurrentHashMap credentials = new ConcurrentHashMap<>(); +credentials.put("username", "foo"); +credentials.put("password", "bar"); + +kuzzle.getAuthController().login("local", credentials).get(); +Boolean result = kuzzle.getAuthController().validateMyCredentials("local", credentials).get(); diff --git a/doc/3/controllers/auth/validate-my-credentials/snippets/validate-my-credentials.test.yml b/doc/3/controllers/auth/validate-my-credentials/snippets/validate-my-credentials.test.yml new file mode 100644 index 00000000..cd4a836a --- /dev/null +++ b/doc/3/controllers/auth/validate-my-credentials/snippets/validate-my-credentials.test.yml @@ -0,0 +1,7 @@ +name: Auth#ValidateMyCredentials +description: Validates the current user's credentials for the specified strategy. +hooks: + before: curl -X POST kuzzle:7512/users/foo/_create -H "Content-Type:application/json" --data '{"content":{"profileIds":["default"]},"credentials":{"local":{"username":"foo","password":"bar"}}}' + after: curl -X DELETE kuzzle:7512/users/foo +template: print-result +expected: [true] diff --git a/doc/3/controllers/collection/create/index.md b/doc/3/controllers/collection/create/index.md new file mode 100644 index 00000000..856848fb --- /dev/null +++ b/doc/3/controllers/collection/create/index.md @@ -0,0 +1,64 @@ +--- +code: true +type: page +title: create +description: Creates a new collection +--- + +# create + +Creates a new [collection](/core/2/guides/essentials/store-access-data) in Kuzzle via the persistence engine, in the provided index. + +You can also provide an optional data mapping that allows you to exploit the full capabilities of our +persistent data storage layer, [ElasticSearch](https://www.elastic.co/elastic-stack) (check here the [mapping capabilities of ElasticSearch](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/mapping.html)). + +This method will only update the mapping if the collection already exists. + +
+ +--- + +## Arguments + +```java +public CompletableFuture create( + final String index, + final String collection, + final ConcurrentHashMap mapping) +throws NotConnectedException, InternalException + +public CompletableFuture create( + final String index, + final String collection) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `mapping` |
ConcurrentHashMap
| Describes the data mapping to associate to the new collection, using Elasticsearch [mapping format](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/mapping.html) | + +--- + +### mapping + +A `ConcurrentHashMap` representing the data mapping of the collection. + +The mapping must have a root field `properties` that contain the mapping definition: + +```java + ConcurrentHashMap mapping = new ConcurrentHashMap<>(); + ConcurrentHashMap properties = new ConcurrentHashMap<>(); + ConcurrentHashMap field = new ConcurrentHashMap<>(); + + field.put("type", "keyword"); + properties.put("field", field); + mapping.put("properties", properties); +``` + +More information about database mappings [here](/core/2/guides/essentials/database-mappings). + +## Usage + +<<< ./snippets/create.java diff --git a/doc/3/controllers/collection/create/snippets/create.java b/doc/3/controllers/collection/create/snippets/create.java new file mode 100644 index 00000000..2e59f164 --- /dev/null +++ b/doc/3/controllers/collection/create/snippets/create.java @@ -0,0 +1,10 @@ + ConcurrentHashMap mapping = new ConcurrentHashMap<>(); + ConcurrentHashMap properties = new ConcurrentHashMap<>(); + ConcurrentHashMap license = new ConcurrentHashMap<>(); + + license.put("type", "keyword"); + properties.put("license", license); + mapping.put("properties", properties); + + kuzzle.getCollectionController().create("nyc-open-data", "yellow-taxi", mapping) + .get(); \ No newline at end of file diff --git a/doc/3/controllers/collection/create/snippets/create.test.yml b/doc/3/controllers/collection/create/snippets/create.test.yml new file mode 100644 index 00000000..ad25ec5b --- /dev/null +++ b/doc/3/controllers/collection/create/snippets/create.test.yml @@ -0,0 +1,9 @@ +name: collection#create +description: Creates a new collection +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/collection/delete-specifications/index.md b/doc/3/controllers/collection/delete-specifications/index.md new file mode 100644 index 00000000..e07a9d8f --- /dev/null +++ b/doc/3/controllers/collection/delete-specifications/index.md @@ -0,0 +1,33 @@ +--- +code: true +type: page +title: deleteSpecifications +description: Delete validation specifications for a collection +--- + +# deleteSpecifications + +Deletes validation specifications for a collection. + +
+ +```java + public CompletableFuture deleteSpecifications( + final String index, + final String collection) +``` + +
+ +| Arguments | Type | Description | +| ------------ | ----------------- | --------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | + +## Returns + +Returns a `CompletableFuture`. + +## Usage + +<<< ./snippets/delete-specifications.java \ No newline at end of file diff --git a/doc/3/controllers/collection/delete-specifications/snippets/delete-specifications.java b/doc/3/controllers/collection/delete-specifications/snippets/delete-specifications.java new file mode 100644 index 00000000..bff98d89 --- /dev/null +++ b/doc/3/controllers/collection/delete-specifications/snippets/delete-specifications.java @@ -0,0 +1,4 @@ + kuzzle + .getCollectionController() + .deleteSpecifications("nyc-open-data", "yellow-taxi") + .get(); \ No newline at end of file diff --git a/doc/3/controllers/collection/delete-specifications/snippets/delete-specifications.test.yml b/doc/3/controllers/collection/delete-specifications/snippets/delete-specifications.test.yml new file mode 100644 index 00000000..56cd44ca --- /dev/null +++ b/doc/3/controllers/collection/delete-specifications/snippets/delete-specifications.test.yml @@ -0,0 +1,7 @@ +name: collection#deleteSpecifications +description: Delete validation specifications for a collection +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create && curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/collection/exists/index.md b/doc/3/controllers/collection/exists/index.md new file mode 100644 index 00000000..7e988d86 --- /dev/null +++ b/doc/3/controllers/collection/exists/index.md @@ -0,0 +1,39 @@ +--- +code: true +type: page +title: exists +description: Checks if a collection exists +--- + +# exists + +Checks if a collection exists. + +--- + +## Arguments + +```java +public CompletableFuture exists( + final String index, + final String collection) +throws NotConnectedException, InternalException + +``` + +--- + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | + +--- + +## Return + +Returns a boolean. + +## Usage + +<<< ./snippets/exists.java diff --git a/doc/3/controllers/collection/exists/snippets/exists.java b/doc/3/controllers/collection/exists/snippets/exists.java new file mode 100644 index 00000000..31359784 --- /dev/null +++ b/doc/3/controllers/collection/exists/snippets/exists.java @@ -0,0 +1,4 @@ +Boolean result = kuzzle + .getCollectionController() + .exists("nyc-open-data", "yellow-taxi") + .get(); diff --git a/doc/3/controllers/collection/exists/snippets/exists.test.yml b/doc/3/controllers/collection/exists/snippets/exists.test.yml new file mode 100644 index 00000000..f4f8e8db --- /dev/null +++ b/doc/3/controllers/collection/exists/snippets/exists.test.yml @@ -0,0 +1,10 @@ +name: collection#exists +description: Check if collection exists +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: print-result +expected: "true" \ No newline at end of file diff --git a/doc/3/controllers/collection/get-mapping/index.md b/doc/3/controllers/collection/get-mapping/index.md new file mode 100644 index 00000000..e38a7371 --- /dev/null +++ b/doc/3/controllers/collection/get-mapping/index.md @@ -0,0 +1,33 @@ +--- +code: true +type: page +title: getMapping +description: Return collection mapping +--- + +# getMapping + +Returns the collection mapping. + +
+ +```java +public CompletableFuture> getMapping( + final String index, + final String collection) throws NotConnectedException, InternalException +``` + +
+ +| Arguments | Type | Description | +| ------------ | ----------------- | --------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | + +## Returns + +Returns a `ConcurrentHashMap` representing the collection mapping. + +## Usage + +<<< ./snippets/get-mapping.js \ No newline at end of file diff --git a/doc/3/controllers/collection/get-mapping/snippets/get-mapping.java b/doc/3/controllers/collection/get-mapping/snippets/get-mapping.java new file mode 100644 index 00000000..bef31262 --- /dev/null +++ b/doc/3/controllers/collection/get-mapping/snippets/get-mapping.java @@ -0,0 +1,25 @@ +ConcurrentHashMap result = kuzzle + .getCollectionController() + .getMapping("nyc-open-data", "yellow-taxi") + .get(); + +/* +{ + _meta={ + schema={}, + allowForm=false + }, + dynamic=true, + properties={ + key={ + type=text, + fields={ + keyword={ + ignore_above=256, + type=keyword + } + } + } + } + } +*/ \ No newline at end of file diff --git a/doc/3/controllers/collection/get-mapping/snippets/get-mapping.test.yml b/doc/3/controllers/collection/get-mapping/snippets/get-mapping.test.yml new file mode 100644 index 00000000..e8f34817 --- /dev/null +++ b/doc/3/controllers/collection/get-mapping/snippets/get-mapping.test.yml @@ -0,0 +1,7 @@ +name: collection#getMapping +description: Return collection mapping +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create && curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: print-result +expected: "true" \ No newline at end of file diff --git a/doc/3/controllers/collection/get-specifications/index.md b/doc/3/controllers/collection/get-specifications/index.md new file mode 100644 index 00000000..3874bcef --- /dev/null +++ b/doc/3/controllers/collection/get-specifications/index.md @@ -0,0 +1,33 @@ +--- +code: true +type: page +title: getSpecifications +description: Returns the validation specifications +--- + +# getSpecifications + +Returns the validation specifications associated to the given index and collection. + +
+ +```java + public CompletableFuture> getSpecifications( + final String index, + final String collection) +``` + +
+ +| Arguments | Type | Description | +| ------------ | ----------------- | --------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | + +## Returns + +Returns a `ConcurrentHashMap` representing the collection specifications. + +## Usage + +<<< ./snippets/get-specifications.java \ No newline at end of file diff --git a/doc/3/controllers/collection/get-specifications/snippets/get-specifications.java b/doc/3/controllers/collection/get-specifications/snippets/get-specifications.java new file mode 100644 index 00000000..96aa0edb --- /dev/null +++ b/doc/3/controllers/collection/get-specifications/snippets/get-specifications.java @@ -0,0 +1,21 @@ + ConcurrentHashMap result = kuzzle + .getCollectionController() + .getSpecifications("nyc-open-data", "yellow-taxi") + .get(); + +/* + { + collection="yellow-taxi", + index="nyc-open-data", + validation={ + fields={ + age={ + defaultValue=42, + mandatory=true, + type="integer" + } + }, + strict=true + } + } +*/ \ No newline at end of file diff --git a/doc/3/controllers/collection/get-specifications/snippets/get-specifications.test.yml b/doc/3/controllers/collection/get-specifications/snippets/get-specifications.test.yml new file mode 100644 index 00000000..5f7533bf --- /dev/null +++ b/doc/3/controllers/collection/get-specifications/snippets/get-specifications.test.yml @@ -0,0 +1,11 @@ +name: collection#getSpecifications +description: Returns the validation specifications +hooks: + before: | + curl -X DELETE kuzzle:7512/nyc-open-data + curl -X POST kuzzle:7512/nyc-open-data/_create + curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -X PUT -H "Content-Type: application/json" -d '{ "strict": false, "fields": {"license": {"type": "string"} } }' kuzzle:7512/nyc-open-data/yellow-taxi/_specifications + after: +template: print-result +expected: 'fields' \ No newline at end of file diff --git a/doc/3/controllers/collection/index.md b/doc/3/controllers/collection/index.md new file mode 100644 index 00000000..bf3a499d --- /dev/null +++ b/doc/3/controllers/collection/index.md @@ -0,0 +1,8 @@ +--- +code: true +type: branch +title: Collection +description: Collection Controller +--- + +# Collection Controller \ No newline at end of file diff --git a/doc/3/controllers/collection/list/index.md b/doc/3/controllers/collection/list/index.md new file mode 100644 index 00000000..646eaf6f --- /dev/null +++ b/doc/3/controllers/collection/list/index.md @@ -0,0 +1,45 @@ +--- +code: true +type: page +title: list +description: Returns the collection list of an index +--- + +# list + +Returns the list of collections associated to a provided index. +The returned list is sorted in alphanumerical order. + +
+ +```java +public CompletableFuture> list( + final String index) throws NotConnectedException, InternalException +``` + + +| Arguments | Type | Description | +| --------- | ---------------------- | ------------- | +| `index` |
String
| Index name | + +## Returns + +Returns a `ConcurrentHashMap` containing the following properties: + +| Property | Type | Description | +| ------------- | ------------------- | ------------------------------------------------------------------ | +| `type` |
String
| Types of returned collections
(`all`, `realtime` or `stored`) | +| `collections` |
ArrayList | List of collections                                                |
+| `from`        | 
Integer
| Offset of the first result | +| `size` |
Integer
| Maximum number of returned results | + +Each object in the `collections` array contains the following properties: + +| Property | Type | Description | +| -------- | ----------------- | ---------------------------------------- | +| `name` |
String
| Collection name | +| `type` |
String
| Collection type (`realtime` or `stored`) | + +## Usage + +<<< ./snippets/list.java \ No newline at end of file diff --git a/doc/3/controllers/collection/list/snippets/list.java b/doc/3/controllers/collection/list/snippets/list.java new file mode 100644 index 00000000..05bd5975 --- /dev/null +++ b/doc/3/controllers/collection/list/snippets/list.java @@ -0,0 +1,22 @@ + ConcurrentHashMap result = kuzzle + .getCollectionController() + .list("nyc-open-data") + .get(); + +/* + { + size=10, + collections=[ + { + name=dark-taxi, + type=stored + }, + { + name=pink-taxi, + type=stored + } + ], + from=0, + type=all + } + */ \ No newline at end of file diff --git a/doc/3/controllers/collection/list/snippets/list.test.yml b/doc/3/controllers/collection/list/snippets/list.test.yml new file mode 100644 index 00000000..b748fa01 --- /dev/null +++ b/doc/3/controllers/collection/list/snippets/list.test.yml @@ -0,0 +1,7 @@ +name: collection#list +description: Returns the collection list of an index +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create && curl -X PUT kuzzle:7512/nyc-open-data/pink-taxi && curl -X PUT kuzzle:7512/nyc-open-data/dark-taxi + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/collection/refresh/index.md b/doc/3/controllers/collection/refresh/index.md new file mode 100644 index 00000000..70cfe7be --- /dev/null +++ b/doc/3/controllers/collection/refresh/index.md @@ -0,0 +1,36 @@ +--- +code: true +type: page +title: refresh +description: Forces an Elasticsearch search index update +--- + +# refresh + +When writing or deleting documents in Kuzzle, it can take up to 1 second for search indexes to be updated, making the changes available in search results. + +This API route forces an immediate refresh of search indexes. + +:::info +A refresh operation comes with some performance costs. + +From the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/docs-refresh.html): +> "While a refresh is much lighter than a commit, it still has a performance cost. A manual refresh can be useful when writing tests, but don’t do a manual refresh every time you index a document in production; it will hurt your performance. Instead, your application needs to be aware of the near real-time nature of Elasticsearch and make allowances for it." + +::: + +
+ +```java +public CompletableFuture refresh( + final String index, + final String collection) throws NotConnectedException, InternalException +``` + +## Returns + +Returns a `CompletableFuture`. + +## Usage + +<<< ./snippets/refresh.java diff --git a/doc/3/controllers/collection/refresh/snippets/refresh.java b/doc/3/controllers/collection/refresh/snippets/refresh.java new file mode 100644 index 00000000..0fba71ce --- /dev/null +++ b/doc/3/controllers/collection/refresh/snippets/refresh.java @@ -0,0 +1,4 @@ + kuzzle + .getCollectionController() + .refresh("nyc-open-data", "yellow-taxi") + .get(); \ No newline at end of file diff --git a/doc/3/controllers/collection/refresh/snippets/refresh.test.yml b/doc/3/controllers/collection/refresh/snippets/refresh.test.yml new file mode 100644 index 00000000..017b05ab --- /dev/null +++ b/doc/3/controllers/collection/refresh/snippets/refresh.test.yml @@ -0,0 +1,10 @@ +--- +name: index#refresh +description: Forces an Elasticsearch search index update +hooks: + before: | + curl -X POST kuzzle:7512/nyc-open-data/_create + curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/collection/search-specifications/index.md b/doc/3/controllers/collection/search-specifications/index.md new file mode 100644 index 00000000..c51aa725 --- /dev/null +++ b/doc/3/controllers/collection/search-specifications/index.md @@ -0,0 +1,65 @@ +--- +code: true +type: page +title: searchSpecifications +description: Search for specifications +--- + +# searchSpecifications + + +Searches collection specifications. + +There is a limit to how many items can be returned by a single search query. +That limit is by default set at 10000, and you can't get over it even with the from and size pagination options. + +:::info +When processing a large number of items (i.e. more than 1000), it is advised to paginate the results using [SearchResult.next](/sdk/java/3/core-classes/search-result/next) rather than increasing the size parameter. +::: + +
+ +```java +public CompletableFuture searchSpecifications( + final ConcurrentHashMap searchQuery, + final SearchOptions options) throws NotConnectedException, InternalException + +public CompletableFuture searchSpecifications( + final ConcurrentHashMap searchQuery) throws NotConnectedException, InternalException +``` + +
+ +| Arguments | Type | Description | +| --------- | ----------------- | ------------------------------------- | +| `searchQuery` |
ConcurrentHashMap
| An object containing the search query | +| `options` |
SearchOptions
| Query options | + +### searchQuery body properties: + +- `query`: the search query itself, using the [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl.html) syntax. +- `aggregations`: control how the search results should be [aggregated](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/search-aggregations.html) +- `sort`: contains a list of fields, used to [sort search results](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/search-request-sort.html), in order of importance. + +An empty body matches all documents in the queried collection. + +### options + +A [SearchOptions](/sdk/java/3/core-classes/search-options) object. + +The following options can be set: + +| Options | Type
(default) | Description | +| ---------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `from` |
Integer

(`0`) | Offset of the first document to fetch | +| `size` |
Integer

(`10`) | Maximum number of documents to retrieve per page | +| `scroll` |
String

(`""`) | When set, gets a forward-only cursor having its ttl set to the given value (ie `1s`; cf [elasticsearch time limits](https://www.elastic.co/guide/en/elasticsearch/reference/7.3/common-options.html#time-units)) | + + ## Return + + Returns a [SearchResult](/sdk/java/3/core-classes/search-result) object. + + +## Usage + +<<< ./snippets/search-specifications.java diff --git a/doc/3/controllers/collection/search-specifications/snippets/search-specifications.java b/doc/3/controllers/collection/search-specifications/snippets/search-specifications.java new file mode 100644 index 00000000..aabb4bd7 --- /dev/null +++ b/doc/3/controllers/collection/search-specifications/snippets/search-specifications.java @@ -0,0 +1,44 @@ + +ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); +ConcurrentHashMap filters = new ConcurrentHashMap<>(); +ConcurrentHashMap args = new ConcurrentHashMap<>(); + +filters.put("match_all", args); +searchQuery.put("query", filters); + +SearchOptions options = new SearchOptions(); +options.setSize(50); +options.setFrom(0); +options.setScroll("10s"); + +SearchResult result = kuzzle + .getCollectionController() + .searchSpecifications(searchQuery, options).get(); + +System.out.println("fetched: " + result.fetched); + /* + { + "total"=1, + "hits"=[ + { + "_index"="%kuzzle", + "_type"="validations", + "_id"="nyc-open-data#yellow-taxi", + "_score"=1, + "_source"={ + "validation"={ + "strict"=false, + "fields"={ + "license"={ + "type"="string" + } + } + }, + "index"="nyc-open-data", + "collection"="yellow-taxi" + } + } + ], + "scrollId"="DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAACSFlgtZTJFYjNiU1FxQzhSNUFpNlZHZGcAAAAAAAAAkxZYLWUyRWIzYlNRcUM4UjVBaTZWR2RnAAAAAAAAAJQWWC1lMkViM2JTUXFDOFI1QWk2VkdkZwAAAAAAAACVFlgtZTJFYjNiU1FxQzhSNUFpNlZHZGcAAAAAAAAAlhZYLWUyRWIzYlNRcUM4UjVBaTZWR2Rn" + } + */ \ No newline at end of file diff --git a/doc/3/controllers/collection/search-specifications/snippets/search-specifications.test.yml b/doc/3/controllers/collection/search-specifications/snippets/search-specifications.test.yml new file mode 100644 index 00000000..c17b1b58 --- /dev/null +++ b/doc/3/controllers/collection/search-specifications/snippets/search-specifications.test.yml @@ -0,0 +1,17 @@ +name: collection#searchSpecifications +description: Search for specifications +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -X POST kuzzle:7512/nyc-open-data/_create + curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -X PUT -H "Content-Type: application/json" -d '{ + "strict": false, + "fields": { + "license": { + "type": "string" + } + } + }' kuzzle:7512/nyc-open-data/yellow-taxi/_specifications?refresh=wait_for +template: default +expected: 'fetched: 1' \ No newline at end of file diff --git a/doc/3/controllers/collection/truncate/index.md b/doc/3/controllers/collection/truncate/index.md new file mode 100644 index 00000000..a8819665 --- /dev/null +++ b/doc/3/controllers/collection/truncate/index.md @@ -0,0 +1,29 @@ +--- +code: true +type: page +title: truncate +description: Remove all documents from a collection +--- + +# truncate + +Removes all documents from a collection, while keeping the associated mappings. + +
+ +```java +public CompletableFuture truncate( + final String index, + final String collection) throws NotConnectedException, InternalException +``` + +
+ +| Arguments | Type | Description | +| ------------ | ----------------- | --------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | + +## Usage + +<<< ./snippets/truncate.js diff --git a/doc/3/controllers/collection/truncate/snippets/truncate.java b/doc/3/controllers/collection/truncate/snippets/truncate.java new file mode 100644 index 00000000..4a458b15 --- /dev/null +++ b/doc/3/controllers/collection/truncate/snippets/truncate.java @@ -0,0 +1 @@ + kuzzle.getCollectionController().truncate("nyc-open-data", "yellow-taxi").get(); \ No newline at end of file diff --git a/doc/3/controllers/collection/truncate/snippets/truncate.test.yml b/doc/3/controllers/collection/truncate/snippets/truncate.test.yml new file mode 100644 index 00000000..931b0041 --- /dev/null +++ b/doc/3/controllers/collection/truncate/snippets/truncate.test.yml @@ -0,0 +1,7 @@ +name: collection#truncate +description: Remove all documents from collection +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create && curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/collection/update-specifications/index.md b/doc/3/controllers/collection/update-specifications/index.md new file mode 100644 index 00000000..35bfa067 --- /dev/null +++ b/doc/3/controllers/collection/update-specifications/index.md @@ -0,0 +1,43 @@ +--- +code: true +type: page +title: updateSpecifications +description: Update the validation specifications +--- + +# updateSpecifications + +The updateSpecifications method allows you to create or update the validation specifications for a collection. + +When the validation specification is not formatted correctly, a detailed error message is returned to help you to debug. + +
+ +```java +public CompletableFuture> updateSpecifications( + final String index, + final String collection, + final ConcurrentHashMap specifications) +``` + +
+ +| Arguments | Type | Description | +| ---------------- | -------------------------------------------- | ------------------------ | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `specifications` |
ConcurrentHashMap
| Specifications to update | + +### specifications + +A `ConcurrentHashMap` representing the specifications. + +It must follow the [Specification Structure](/core/2/guides/essentials/data-validation). + +## Returns + +Returns a `ConcurrentHashMap` containing the specifications. + +## Usage + +<<< ./snippets/update-specifications.java \ No newline at end of file diff --git a/doc/3/controllers/collection/update-specifications/snippets/update-specifications.java b/doc/3/controllers/collection/update-specifications/snippets/update-specifications.java new file mode 100644 index 00000000..e627ca17 --- /dev/null +++ b/doc/3/controllers/collection/update-specifications/snippets/update-specifications.java @@ -0,0 +1,26 @@ + ConcurrentHashMap specifications = new ConcurrentHashMap<>(); + ConcurrentHashMap fields = new ConcurrentHashMap<>(); + ConcurrentHashMap license = new ConcurrentHashMap<>(); + + specifications.put("strict", false); + license.put("mandatory", true); + license.put("type", "string"); + fields.put("license", license); + specifications.put("fields", fields); + + ConcurrentHashMap result = kuzzle + .getCollectionController() + .updateSpecifications("nyc-open-data", "yellow-taxi", specifications) + .get(); + +/* + { + strict=false, + fields={ + license={ + mandatory=true, + type="string" + } + } + } + */ diff --git a/doc/3/controllers/collection/update-specifications/snippets/update-specifications.test.yml b/doc/3/controllers/collection/update-specifications/snippets/update-specifications.test.yml new file mode 100644 index 00000000..288fc2e5 --- /dev/null +++ b/doc/3/controllers/collection/update-specifications/snippets/update-specifications.test.yml @@ -0,0 +1,9 @@ +name: collection#updateSpecifications +description: Update the validation specifications +hooks: + before: | + curl -X POST kuzzle:7512/nyc-open-data/_create + curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi/ + after: curl -X DELETE kuzzle:7512/nyc-open-data/yellow-taxi/_specifications +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/collection/validate-specifications/index.md b/doc/3/controllers/collection/validate-specifications/index.md new file mode 100644 index 00000000..c3fb13c1 --- /dev/null +++ b/doc/3/controllers/collection/validate-specifications/index.md @@ -0,0 +1,51 @@ +--- +code: true +type: page +title: validateSpecifications +description: Validate specifications format +--- + +# validateSpecifications + +The validateSpecifications method checks if a validation specification is well formatted. It does not store or modify the existing specification. + +When the validation specification is not formatted correctly, a detailed error message is returned to help you to debug. + +
+ +```java + public CompletableFuture> validateSpecifications( + final String index, + final String collection, + final ConcurrentHashMap specifications) +``` + +
+ +| Arguments | Type | Description | +| ---------------- | -------------------------------------------- | -------------------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `specifications` |
ConcurrentHashMap
| Specifications to validate | + +### specifications + +A `ConcurrentHashMap` representing the specifications. + +This object must follow the [Specification Structure](/core/2/guides/cookbooks/datavalidation). + +## Returns + +Returns a `ConcurrentHashMap` which contains information about the specifications validity. + +It contains the following properties: + +| Property | Type | Description | +| ------------- | ---------------------------- | ---------------------------- | +| `valid` |
Boolean
| Specifications validity | +| `details` |
ArrayList
| Specifications errors | +| `description` |
String
| Global description of errors | + +## Usage + +<<< ./snippets/validate-specifications.java \ No newline at end of file diff --git a/doc/3/controllers/collection/validate-specifications/snippets/validate-specifications.java b/doc/3/controllers/collection/validate-specifications/snippets/validate-specifications.java new file mode 100644 index 00000000..69e736cc --- /dev/null +++ b/doc/3/controllers/collection/validate-specifications/snippets/validate-specifications.java @@ -0,0 +1,24 @@ + ConcurrentHashMap specifications = new ConcurrentHashMap<>(); + ConcurrentHashMap fields = new ConcurrentHashMap<>(); + ConcurrentHashMap license = new ConcurrentHashMap<>(); + + specifications.put("strict", false); + license.put("mandatory", true); + license.put("type", "symbol"); // type 'symbol' is not a recognized type + fields.put("license", license); + specifications.put("fields", fields); + + ConcurrentHashMap result = kuzzle + .getCollectionController() + .validateSpecifications("nyc-open-data", "yellow-taxi", specifications) + .get(); + +/* + { + valid=false, + details=[ + "In nyc-open-data.yellow-taxi.license: symbol is not a recognized type." + ], + description="Some errors with provided specifications." + } +*/ \ No newline at end of file diff --git a/doc/3/controllers/collection/validate-specifications/snippets/validate-specifications.test.yml b/doc/3/controllers/collection/validate-specifications/snippets/validate-specifications.test.yml new file mode 100644 index 00000000..b5f42d87 --- /dev/null +++ b/doc/3/controllers/collection/validate-specifications/snippets/validate-specifications.test.yml @@ -0,0 +1,7 @@ +name: collection#validateSpecifications +description: Validate specifications format +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create && curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: print-result +expected: Some errors with provided specifications. \ No newline at end of file diff --git a/doc/3/controllers/document/count/index.md b/doc/3/controllers/document/count/index.md new file mode 100644 index 00000000..7be36d87 --- /dev/null +++ b/doc/3/controllers/document/count/index.md @@ -0,0 +1,53 @@ +--- +code: true +type: page +title: count +description: Counts documents in a collection. +--- + +# count + +Counts documents in a collection. + +A query can be provided to alter the count result, otherwise returns the total number of documents in the collection. + +Kuzzle uses the [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl.html) syntax. + +--- + +## Arguments + +```java +public CompletableFuture count( + final String index, + final String collection) +throws NotConnectedException, InternalException + +``` + +```java +public CompletableFuture count( + final String index, + final String collection, + final ConcurrentHaspMap searchQuery) +throws NotConnectedException, InternalException + +``` + +--- + +| Argument | Type | Description | +| ------------------ | -------------------------------------------- | --------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `searchQuery` |
ConcurrentHashMap
| Query to match | + +--- + +## Return + +Returns an Integer. + +## Usage + +<<< ./snippets/count.java diff --git a/doc/3/controllers/document/count/snippets/count.java b/doc/3/controllers/document/count/snippets/count.java new file mode 100644 index 00000000..9fd3ad56 --- /dev/null +++ b/doc/3/controllers/document/count/snippets/count.java @@ -0,0 +1,8 @@ + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + searchQuery.put("match", match); + Integer result = kuzzle + .getDocumentController() + .count("nyc-open-data", "yellow-taxi", searchQuery) + .get(); \ No newline at end of file diff --git a/doc/3/controllers/document/count/snippets/count.test.yml b/doc/3/controllers/document/count/snippets/count.test.yml new file mode 100644 index 00000000..4e7b4670 --- /dev/null +++ b/doc/3/controllers/document/count/snippets/count.test.yml @@ -0,0 +1,18 @@ +--- +name: document#count +description: Counts documents matching the given query +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + for i in 1 2 3 4 5; do + curl -H "Content-type: application/json" -d '{"Hello": "Clarisse"}' kuzzle:7512/nyc-open-data/yellow-taxi/_create + done + for i in 1 2 3 4 5; do + curl -H "Content-type: application/json" -d '{}' kuzzle:7512/nyc-open-data/yellow-taxi/_create + done + curl -XPOST kuzzle:7512/nyc-open-data/yellow-taxi/_refresh + after: +template: print-result +expected: 5 \ No newline at end of file diff --git a/doc/3/controllers/document/create-or-replace/index.md b/doc/3/controllers/document/create-or-replace/index.md new file mode 100644 index 00000000..1a3ef99f --- /dev/null +++ b/doc/3/controllers/document/create-or-replace/index.md @@ -0,0 +1,55 @@ +--- +code: true +type: page +title: createOrReplace +description: Creates or replaces a document +--- + +# createOrReplace + +Creates a new document in the persistent data storage, or replaces its content if it already exists. + +--- + +## Arguments + +```java +public CompletableFuture> createOrReplace( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document) +throws NotConnectedException, InternalException + +public CompletableFuture> createOrReplace( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document, + final Boolean waitForRefresh) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `id` |
String
| Document ID | +| `document` |
ConcurrentHashMap
| Document content | +| `waitForRefresh` |
Boolean
| If set to `true`, Kuzzle will wait for the persistence layer to finish indexing| + +--- + +## Return + +A `ConcurrentHashMap` which has the following properties: + +| Property | Type | Description | +|------------- |----------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Document content | +| `_id` |
String
| ID of the document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +## Usage + +<<< ./snippets/create-or-replace.java diff --git a/doc/3/controllers/document/create-or-replace/snippets/create-or-replace.java b/doc/3/controllers/document/create-or-replace/snippets/create-or-replace.java new file mode 100644 index 00000000..f88a3796 --- /dev/null +++ b/doc/3/controllers/document/create-or-replace/snippets/create-or-replace.java @@ -0,0 +1,25 @@ + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("firstname", "John"); + + ConcurrentHashMap result = kuzzle + .getDocumentController() + .createOrReplace("nyc-open-data", "yellow-taxi", "some-id", document) + .get(); + +/* + { + _source= + { + firstname=John, + _kuzzle_info={ + createdAt=1582892323254, + author=-1, + updatedAt=1582892323254, + updater=-1 + } + }, + _id=some-id, + _version=1 + } + */ diff --git a/doc/3/controllers/document/create-or-replace/snippets/create-or-replace.test.yml b/doc/3/controllers/document/create-or-replace/snippets/create-or-replace.test.yml new file mode 100644 index 00000000..fe3e45b8 --- /dev/null +++ b/doc/3/controllers/document/create-or-replace/snippets/create-or-replace.test.yml @@ -0,0 +1,10 @@ +name: document#createOrReplace +description: Creates or Replace a document +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: print-result +expected: "firstname=John" \ No newline at end of file diff --git a/doc/3/controllers/document/create/index.md b/doc/3/controllers/document/create/index.md new file mode 100644 index 00000000..5c3041fd --- /dev/null +++ b/doc/3/controllers/document/create/index.md @@ -0,0 +1,68 @@ +--- +code: true +type: page +title: create +description: Creates a new document +--- + +# create + +Creates a new document in the persistent data storage. + +Throws an error if the document already exists. + +The optional parameter `waitForRefresh` can be used with the value `true` in order to wait for the document to be indexed (indexed documents are available for `search`). + +--- + +## Arguments + +```java +public CompletableFuture> create( + final String index, + final String collection, + final ConcurrentHashMap document) +throws NotConnectedException, InternalException + +public CompletableFuture> create( + final String index, + final String collection, + final ConcurrentHashMap document, + final CreateOptions options) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `document` |
ConcurrentHashMap
| Document content | +| `options` |
CreateOptions

(`null`) | Create options | + +--- + +### options + +A [CreateOptions](/sdk/java/3/core-classes/create-options) object. + +The following options can be set: + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `id` |
String
(optional) | Document identifier. Auto-generated if not specified | +| `waitForRefresh` |
Boolean
(optional) | If set to `true`, Kuzzle will wait for the persistence layer to finish indexing| + + +## Return + +A `ConcurrentHashMap` which has the following properties: + +| Property | Type | Description | +|------------- |----------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Created document | +| `_id` |
String
| ID of the newly created document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +## Usage + +<<< ./snippets/create.java diff --git a/doc/3/controllers/document/create/snippets/create.java b/doc/3/controllers/document/create/snippets/create.java new file mode 100644 index 00000000..b5369d3a --- /dev/null +++ b/doc/3/controllers/document/create/snippets/create.java @@ -0,0 +1,18 @@ + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("firstname", "John"); + + ConcurrentHashMap result = kuzzle.getDocumentController().create("nyc-open-data", "yellow-taxi", document) + .get(); + +/* result = + { + _source= + { + firstname=John, + _kuzzle_info={ createdAt=1582891678488, author=-1 } + }, + _id=mDmyi3ABYMAjFJ_ZO-EZ, + _version=1 + } +*/ \ No newline at end of file diff --git a/doc/3/controllers/document/create/snippets/create.test.yml b/doc/3/controllers/document/create/snippets/create.test.yml new file mode 100644 index 00000000..823badff --- /dev/null +++ b/doc/3/controllers/document/create/snippets/create.test.yml @@ -0,0 +1,10 @@ +name: document#create +description: Creates a new document +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: print-result +expected: "firstname=John" \ No newline at end of file diff --git a/doc/3/controllers/document/delete-by-query/index.md b/doc/3/controllers/document/delete-by-query/index.md new file mode 100644 index 00000000..c59a5abc --- /dev/null +++ b/doc/3/controllers/document/delete-by-query/index.md @@ -0,0 +1,46 @@ +--- +code: true +type: page +title: deleteByQuery +description: Delete documents matching query +--- + +# deleteByQuery + +Deletes documents matching the provided search query. + +Kuzzle uses the [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl.html) syntax. + +An empty or null query will match all documents in the collection. + +
+ +```java + public CompletableFuture> deleteByQuery( + final String index, + final String collection, + final ConcurrentHashMap searchQuery) throws NotConnectedException, InternalException + + public CompletableFuture> deleteByQuery( + final String index, + final String collection, + final ConcurrentHashMap searchQuery, + final Boolean waitForRefresh) throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +| ------------------ | -------------------------------------------- | --------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `searchQuery` |
ConcurrentHashMap
| Query to match | +| `waitForRefresh` |
Boolean
(optional) | If set to `true`, Kuzzle will wait for the persistence layer to finish indexing| + +--- + +## Returns + +Returns an `ArrayList` containing the deleted document ids. + +## Usage + +<<< ./snippets/delete-by-query.js \ No newline at end of file diff --git a/doc/3/controllers/document/delete-by-query/snippets/delete-by-query.java b/doc/3/controllers/document/delete-by-query/snippets/delete-by-query.java new file mode 100644 index 00000000..46b10a9a --- /dev/null +++ b/doc/3/controllers/document/delete-by-query/snippets/delete-by-query.java @@ -0,0 +1,10 @@ + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("capacity", 4); + query.put("match", match); + searchQuery.put("query", query); + ArrayList result = kuzzle + .getDocumentController() + .deleteByQuery("nyc-open-data", "yellow-taxi", searchQuery) + .get(); diff --git a/doc/3/controllers/document/delete-by-query/snippets/delete-by-query.test.yml b/doc/3/controllers/document/delete-by-query/snippets/delete-by-query.test.yml new file mode 100644 index 00000000..5d3fd03d --- /dev/null +++ b/doc/3/controllers/document/delete-by-query/snippets/delete-by-query.test.yml @@ -0,0 +1,22 @@ +name: document#deleteByQuery +description: Delete documents matching query +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + for i in 1 2 3 4 5; do + curl -H "Content-type: application/json" -d '{"capacity": 4}' kuzzle:7512/nyc-open-data/yellow-taxi/document_$i/_create + done + for i in 1 2 3 4 5; do + curl -H "Content-type: application/json" -d '{"capacity": 7}' kuzzle:7512/nyc-open-data/yellow-taxi/_create + done + curl -XPOST kuzzle:7512/nyc-open-data/_refresh + after: +template: print-result-arraylist +expected: + - "document_1" + - "document_2" + - "document_3" + - "document_4" + - "document_5" \ No newline at end of file diff --git a/doc/3/controllers/document/delete/index.md b/doc/3/controllers/document/delete/index.md new file mode 100644 index 00000000..67b309aa --- /dev/null +++ b/doc/3/controllers/document/delete/index.md @@ -0,0 +1,50 @@ +--- +code: true +type: page +title: delete +description: Deletes a document +--- + +# delete + +Deletes a document. + +--- + +## Arguments + +```java +public CompletableFuture> delete( + final String index, + final String collection, + final String id) +throws NotConnectedException, InternalException + +public CompletableFuture> delete( + final String index, + final String collection, + final String id, + final Boolean waitForRefresh) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `id ` |
String
| Document ID | +| `waitForRefresh` |
Boolean
(optional) | If set to `true`, Kuzzle will wait for the persistence layer to finish indexing| + +--- + +## Return + +A `ConcurrentHashMap` which has the following property: + +| Property | Type | Description | +|------------- |----------------------------- |--------------------------------- | +| `_id` |
String
| ID of the deleted document | + +## Usage + +<<< ./snippets/delete.java diff --git a/doc/3/controllers/document/delete/snippets/delete.java b/doc/3/controllers/document/delete/snippets/delete.java new file mode 100644 index 00000000..433a71de --- /dev/null +++ b/doc/3/controllers/document/delete/snippets/delete.java @@ -0,0 +1,3 @@ + + kuzzle.getDocumentController().delete("nyc-open-data", "yellow-taxi", "some-id") + .get(); diff --git a/doc/3/controllers/document/delete/snippets/delete.test.yml b/doc/3/controllers/document/delete/snippets/delete.test.yml new file mode 100644 index 00000000..46aeccbb --- /dev/null +++ b/doc/3/controllers/document/delete/snippets/delete.test.yml @@ -0,0 +1,11 @@ +name: document#delete +description: deletes a document +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/document/exists/index.md b/doc/3/controllers/document/exists/index.md new file mode 100644 index 00000000..b682d867 --- /dev/null +++ b/doc/3/controllers/document/exists/index.md @@ -0,0 +1,42 @@ +--- +code: true +type: page +title: exists +description: Checks if a document exists +--- + +# exists + +Checks if a document exists. + +--- + +## Arguments + +```java +public CompletableFuture exists( + final String index, + final String collection, + final String id) +throws NotConnectedException, InternalException + +``` + +--- + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `id ` |
String
| Document ID | + + +--- + +## Return + +Returns a boolean. + +## Usage + +<<< ./snippets/exists.java \ No newline at end of file diff --git a/doc/3/controllers/document/exists/snippets/exists.java b/doc/3/controllers/document/exists/snippets/exists.java new file mode 100644 index 00000000..2121d858 --- /dev/null +++ b/doc/3/controllers/document/exists/snippets/exists.java @@ -0,0 +1,4 @@ +Boolean result = kuzzle + .getDocumentController() + .exists("nyc-open-data", "yellow-taxi", "some-id") + .get(); diff --git a/doc/3/controllers/document/exists/snippets/exists.test.yml b/doc/3/controllers/document/exists/snippets/exists.test.yml new file mode 100644 index 00000000..2f36ca7b --- /dev/null +++ b/doc/3/controllers/document/exists/snippets/exists.test.yml @@ -0,0 +1,11 @@ +name: document#exists +description: Check if document exists +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + after: +template: print-result +expected: "true" \ No newline at end of file diff --git a/doc/3/controllers/document/get/index.md b/doc/3/controllers/document/get/index.md new file mode 100644 index 00000000..d143f19b --- /dev/null +++ b/doc/3/controllers/document/get/index.md @@ -0,0 +1,45 @@ +--- +code: true +type: page +title: get +description: Gets a document +--- + +# get + +Gets a document. + +--- + +## Arguments + +```java +public CompletableFuture> get( + final String index, + final String collection, + final String id) +throws NotConnectedException, InternalException + +``` + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `id ` |
String
| Document ID | + +--- + +## Return + +A `ConcurrentHashMap` which has the following properties: + +| Property | Type | Description | +|------------- |----------------------------- |--------------------------------------------------------------- | +| `_source` |
ConcurrentHashMap
| Document content | +| `_id` |
String
| ID of the document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +## Usage + +<<< ./snippets/get.java diff --git a/doc/3/controllers/document/get/snippets/get.java b/doc/3/controllers/document/get/snippets/get.java new file mode 100644 index 00000000..46119495 --- /dev/null +++ b/doc/3/controllers/document/get/snippets/get.java @@ -0,0 +1,16 @@ + ConcurrentHashMap result = + kuzzle.getDocumentController().get("nyc-open-data", "yellow-taxi", "some-id") + .get(); + +/* + { + _source= + { + key1=value1, + key2=value2, + _kuzzle_info= { createdAt=1582892127577, author=-1} + }, + _id=some-id, + _version=1 + } +*/ diff --git a/doc/3/controllers/document/get/snippets/get.test.yml b/doc/3/controllers/document/get/snippets/get.test.yml new file mode 100644 index 00000000..7c66a85b --- /dev/null +++ b/doc/3/controllers/document/get/snippets/get.test.yml @@ -0,0 +1,11 @@ +name: document#get +description: Get a document from kuzzle +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + after: +template: print-result +expected: "_id=some-id" \ No newline at end of file diff --git a/doc/3/controllers/document/m-create-or-replace/index.md b/doc/3/controllers/document/m-create-or-replace/index.md new file mode 100644 index 00000000..d67f5ecb --- /dev/null +++ b/doc/3/controllers/document/m-create-or-replace/index.md @@ -0,0 +1,70 @@ +--- +code: true +type: page +title: mCreateOrReplace +description: Creates or replaces multiple documents +--- + +# mCreateOrReplace + +Creates or replaces multiple documents. + +--- + +## Arguments + +```java +public CompletableFuture>> mCreateOrReplace( + final String index, + final String collection, + final ArrayList> documents) +throws NotConnectedException, InternalException + +public CompletableFuture>> mCreateOrReplace( + final String index, + final String collection, + final ArrayList> documents, + final Boolean waitForRefresh) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | ------------------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `documents` |
ArrayList>
| ArrayList containing the documents to create | +| `waitForRefresh` |
Boolean
| If set to `true`, Kuzzle will wait for the persistence layer to finish indexing | + +--- + +### documents + +Each document has the following properties: + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `_id` |
String
| Optional document ID. Will be auto-generated if not defined. | +| `body` |
ConcurrentHashMap
| Document body | + +## Return + +A `ConcurrentHashMap>` which has a `successes` and `errors` `ArrayList`: +Each created document is an object of the `successes` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Created document | +| `_id` |
String
| ID of the newly created document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +Each errored document is an object of the `errors` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `document` |
ConcurrentHashMap
| Document that causes the error | +| `status` |
Integer
| HTTP error status | +| `reason` |
String
| Human readable reason | + +## Usage + +<<< ./snippets/m-create-or-replace.java diff --git a/doc/3/controllers/document/m-create-or-replace/snippets/m-create-or-replace.java b/doc/3/controllers/document/m-create-or-replace/snippets/m-create-or-replace.java new file mode 100644 index 00000000..48af041c --- /dev/null +++ b/doc/3/controllers/document/m-create-or-replace/snippets/m-create-or-replace.java @@ -0,0 +1,54 @@ +ConcurrentHashMap document1 = new ConcurrentHashMap<>(); +ConcurrentHashMap document2 = new ConcurrentHashMap<>(); +ConcurrentHashMap body = new ConcurrentHashMap<>(); +ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + +body.put("Agent", "Smith"); +body2.put("Gordon", "Freeman"); + +document1.put("_id", "some-id"); +document1.put("body", body); + +document2.put("_id", "some-id2"); +document2.put("body", body2); + +final ArrayList> documents = new ArrayList<>(); +documents.add(document1); +documents.add(document2); + +ConcurrentHashMap> result = kuzzle + .getDocumentController() + .mCreateOrReplace("nyc-open-data", "yellow-taxi", documents) + .get(); + +/* + result = + { + successes= + [ + { + result=created, + _source= + { + Agent=Smith, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id, + _version=1, + status=201 + }, + { + result=created, + _source= + { + Gordon=Freeman, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id2, + _version=1, + status=201 + } + ], + errors=[] + } +*/ diff --git a/doc/3/controllers/document/m-create-or-replace/snippets/m-create-or-replace.test.yml b/doc/3/controllers/document/m-create-or-replace/snippets/m-create-or-replace.test.yml new file mode 100644 index 00000000..f38114bf --- /dev/null +++ b/doc/3/controllers/document/m-create-or-replace/snippets/m-create-or-replace.test.yml @@ -0,0 +1,12 @@ +name: document#mCreateOrReplace +description: Creates or replaces multiple documents +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: print-result-array +expected: + - "id=some-id, _version=1, status=201" + - "id=some-id2, _version=1, status=201" \ No newline at end of file diff --git a/doc/3/controllers/document/m-create/index.md b/doc/3/controllers/document/m-create/index.md new file mode 100644 index 00000000..f26864fa --- /dev/null +++ b/doc/3/controllers/document/m-create/index.md @@ -0,0 +1,70 @@ +--- +code: true +type: page +title: mCreate +description: Creates multiple documents +--- + +# mCreate + +Creates multiple documents. + +--- + +## Arguments + +```java +public CompletableFuture>> mCreate( + final String index, + final String collection, + final ArrayList> documents) +throws NotConnectedException, InternalException + +public CompletableFuture>> mCreate( + final String index, + final String collection, + final ArrayList> documents, + final Boolean waitForRefresh) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | ------------------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `documents` |
ArrayList>
| ArrayList containing the documents to create | +| `waitForRefresh` |
Boolean
| If set to `true`, Kuzzle will wait for the persistence layer to finish indexing | + +--- + +### documents + +Each document has the following properties: + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `_id` |
String
| Optional document ID. Will be auto-generated if not defined. | +| `body` |
ConcurrentHashMap
| Document body | + +## Return + +A `ConcurrentHashMap>` which has a `successes` and `errors` `ArrayList`: +Each created document is an object of the `successes` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Created document | +| `_id` |
String
| ID of the newly created document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +Each errored document is an object of the `errors` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `document` |
ConcurrentHashMap
| Document that causes the error | +| `status` |
Integer
| HTTP error status | +| `reason` |
String
| Human readable reason | + +## Usage + +<<< ./snippets/m-create.java diff --git a/doc/3/controllers/document/m-create/snippets/m-create.java b/doc/3/controllers/document/m-create/snippets/m-create.java new file mode 100644 index 00000000..24f9696f --- /dev/null +++ b/doc/3/controllers/document/m-create/snippets/m-create.java @@ -0,0 +1,54 @@ +ConcurrentHashMap document1 = new ConcurrentHashMap<>(); +ConcurrentHashMap document2 = new ConcurrentHashMap<>(); +ConcurrentHashMap body = new ConcurrentHashMap<>(); +ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + +body.put("Agent", "Smith"); +body2.put("Gordon", "Freeman"); + +document1.put("_id", "some-id"); +document1.put("body", body); + +document2.put("_id", "some-id2"); +document2.put("body", body2); + +final ArrayList> documents = new ArrayList<>(); +documents.add(document1); +documents.add(document2); + +ConcurrentHashMap> result = kuzzle + .getDocumentController() + .mCreate("nyc-open-data", "yellow-taxi", documents) + .get(); + +/* +result = + { + successes= + [ + { + result=created, + _source= + { + Agent=Smith, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id, + _version=1, + status=201 + }, + { + result=created, + _source= + { + Gordon=Freeman, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id2, + _version=1, + status=201 + } + ], + errors=[] + } +*/ diff --git a/doc/3/controllers/document/m-create/snippets/m-create.test.yml b/doc/3/controllers/document/m-create/snippets/m-create.test.yml new file mode 100644 index 00000000..a513ed5a --- /dev/null +++ b/doc/3/controllers/document/m-create/snippets/m-create.test.yml @@ -0,0 +1,12 @@ +name: document#mCreate +description: Creates multiple documents +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: print-result-array +expected: + - "id=some-id, _version=1, status=201" + - "id=some-id2, _version=1, status=201" \ No newline at end of file diff --git a/doc/3/controllers/document/m-delete/index.md b/doc/3/controllers/document/m-delete/index.md new file mode 100644 index 00000000..d7de90bd --- /dev/null +++ b/doc/3/controllers/document/m-delete/index.md @@ -0,0 +1,46 @@ +--- +code: true +type: page +title: mDelete +description: Deletes multiple documents +--- + +# mDelete + +Deletes multiple documents. + +--- + +## Arguments + +```java +public CompletableFuture>> mDelete( + final String index, + final String collection, + final ArrayList ids) +throws NotConnectedException, InternalException + +``` + +| Arguments | Type | Description | +| ------------------ | ------------------------------------------------------- | --------------------------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `ids` |
ArrayList
| Document IDs | +--- + +## Return + +A `ConcurrentHashMap>` which has a `successes` and `errors` `ArrayList`: +The `successes` array contains the successfully deleted document IDs. + +Each deletion error is an object of the errors array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `_id` |
String
| Document ID | +| `reason` |
String
| Human readable reason | + +## Usage + +<<< ./snippets/m-delete.java \ No newline at end of file diff --git a/doc/3/controllers/document/m-delete/snippets/m-delete.java b/doc/3/controllers/document/m-delete/snippets/m-delete.java new file mode 100644 index 00000000..513b6071 --- /dev/null +++ b/doc/3/controllers/document/m-delete/snippets/m-delete.java @@ -0,0 +1,14 @@ + final ArrayList ids = new ArrayList<>(); + ids.add("some-id"); + ids.add("some-id2"); + + ConcurrentHashMap> result = kuzzle.getDocumentController().mDelete("nyc-open-data", "yellow-taxi", ids) + .get(); +/* + result = + { + successes=[some-id, some-id2], + errors=[] + } + +*/ \ No newline at end of file diff --git a/doc/3/controllers/document/m-delete/snippets/m-delete.test.yml b/doc/3/controllers/document/m-delete/snippets/m-delete.test.yml new file mode 100644 index 00000000..a7dd0966 --- /dev/null +++ b/doc/3/controllers/document/m-delete/snippets/m-delete.test.yml @@ -0,0 +1,14 @@ +name: document#mDelete +description: Delete multiple documents +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"name":"John"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + curl -XPOST -d '{"color":"purple"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id2/_create + after: +template: print-result-array +expected: + - "some-id" + - "some-id2" \ No newline at end of file diff --git a/doc/3/controllers/document/m-get/index.md b/doc/3/controllers/document/m-get/index.md new file mode 100644 index 00000000..4c424036 --- /dev/null +++ b/doc/3/controllers/document/m-get/index.md @@ -0,0 +1,47 @@ +--- +code: true +type: page +title: mGet +description: Gets multiple documents +--- + +# mGet + +Gets multiple documents. + +--- + +## Arguments + +```java +public CompletableFuture>> mGet( + final String index, + final String collection, + final ArrayList ids) +throws NotConnectedException, InternalException + +``` + +| Arguments | Type | Description | +| ------------------ | ------------------------------------------------------- | --------------------------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `ids` |
ArrayList
| Document IDs | +--- + +## Return + +A `ConcurrentHashMap>` which has a `successes` and `errors` `ArrayList`: +Each created document is an object of the `successes` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Document content | +| `_id` |
String
| Document ID | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +The `errors` array contain the IDs of not found documents. + +## Usage + +<<< ./snippets/m-get.java diff --git a/doc/3/controllers/document/m-get/snippets/m-get.java b/doc/3/controllers/document/m-get/snippets/m-get.java new file mode 100644 index 00000000..2e3ad1ab --- /dev/null +++ b/doc/3/controllers/document/m-get/snippets/m-get.java @@ -0,0 +1,37 @@ + final ArrayList ids = new ArrayList<>(); + ids.add("some-id"); + ids.add("some-id2"); + + ConcurrentHashMap> result = kuzzle.getDocumentController().mGet("nyc-open-data", "yellow-taxi", ids) + .get(); + +/* + result = + { + successes= + [ + { + result=created, + _source= + { + key=value, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id, + _version=1 + }, + { + result=created, + _source= + { + key=value, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id2, + _version=1 + } + ], + errors=[] + } + +*/ \ No newline at end of file diff --git a/doc/3/controllers/document/m-get/snippets/m-get.test.yml b/doc/3/controllers/document/m-get/snippets/m-get.test.yml new file mode 100644 index 00000000..0ea219d0 --- /dev/null +++ b/doc/3/controllers/document/m-get/snippets/m-get.test.yml @@ -0,0 +1,14 @@ +name: document#mGet +description: Get multiple documents +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"name":"John"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + curl -XPOST -d '{"color":"purple"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id2/_create + after: +template: print-result-array +expected: + - "id=some-id, _version=1" + - "id=some-id2, _version=1" \ No newline at end of file diff --git a/doc/3/controllers/document/m-replace/index.md b/doc/3/controllers/document/m-replace/index.md new file mode 100644 index 00000000..c70fb82e --- /dev/null +++ b/doc/3/controllers/document/m-replace/index.md @@ -0,0 +1,70 @@ +--- +code: true +type: page +title: mReplace +description: Replaces multiple documents +--- + +# mReplace + +Replaces multiple documents. + +--- + +## Arguments + +```java +public CompletableFuture>> mReplace( + final String index, + final String collection, + final ArrayList> documents) +throws NotConnectedException, InternalException + +public CompletableFuture>> mReplace( + final String index, + final String collection, + final ArrayList> documents, + final Boolean waitForRefresh) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | ------------------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `documents` |
ArrayList>
| ArrayList containing the documents to replace | +| `waitForRefresh` |
Boolean
| If set to `true`, Kuzzle will wait for the persistence layer to finish indexing | + +--- + +### documents + +Each document has the following properties: + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `_id` |
String
| Optional document ID. Will be auto-generated if not defined. | +| `body` |
ConcurrentHashMap
| Document body | + +## Return + +A `ConcurrentHashMap>` which has a `successes` and `errors` `ArrayList`: +Each created document is an object of the `successes` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Created document | +| `_id` |
String
| ID of the replaced document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +Each errored document is an object of the `errors` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `document` |
ConcurrentHashMap
| Document that causes the error | +| `status` |
Integer
| HTTP error status | +| `reason` |
String
| Human readable reason | + +## Usage + +<<< ./snippets/m-replace.java diff --git a/doc/3/controllers/document/m-replace/snippets/m-replace.java b/doc/3/controllers/document/m-replace/snippets/m-replace.java new file mode 100644 index 00000000..f9651db0 --- /dev/null +++ b/doc/3/controllers/document/m-replace/snippets/m-replace.java @@ -0,0 +1,54 @@ +ConcurrentHashMap document1 = new ConcurrentHashMap<>(); +ConcurrentHashMap document2 = new ConcurrentHashMap<>(); +ConcurrentHashMap body = new ConcurrentHashMap<>(); +ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + +body.put("name", "Smith"); +body2.put("name", "Freeman"); + +document1.put("_id", "some-id"); +document1.put("body", body); + +document2.put("_id", "some-id2"); +document2.put("body", body2); + +final ArrayList> documents = new ArrayList<>(); +documents.add(document1); +documents.add(document2); + +ConcurrentHashMap> result = kuzzle + .getDocumentController() + .mReplace("nyc-open-data", "yellow-taxi", documents) + .get(); + +/* + result = + { + successes= + [ + { + result=created, + _source= + { + Agent=Smith, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id, + _version=2, + status=200 + }, + { + result=created, + _source= + { + Gordon=Freeman, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id2, + _version=2, + status=200 + } + ], + errors=[] + } +*/ diff --git a/doc/3/controllers/document/m-replace/snippets/m-replace.test.yml b/doc/3/controllers/document/m-replace/snippets/m-replace.test.yml new file mode 100644 index 00000000..f38b2746 --- /dev/null +++ b/doc/3/controllers/document/m-replace/snippets/m-replace.test.yml @@ -0,0 +1,14 @@ +name: document#mReplace +description: Replaces multiple documents +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"name":"John"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + curl -XPOST -d '{"name":"John"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id2/_create + after: +template: print-result-array +expected: + - "id=some-id, _version=2, status=200" + - "id=some-id2, _version=2, status=200" \ No newline at end of file diff --git a/doc/3/controllers/document/m-update/index.md b/doc/3/controllers/document/m-update/index.md new file mode 100644 index 00000000..fb9a72df --- /dev/null +++ b/doc/3/controllers/document/m-update/index.md @@ -0,0 +1,82 @@ +--- +code: true +type: page +title: mUpdate +description: Updates multiple documents +--- + +# mUpdate + +Updates multiple documents. + +--- + +## Arguments + +```java +public CompletableFuture>> mUpdate( + final String index, + final String collection, + final ArrayList> documents) +throws NotConnectedException, InternalException + +public CompletableFuture>> mUpdate( + final String index, + final String collection, + final ArrayList> documents, + final UpdateOptions options) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | ------------------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `documents` |
ArrayList>
| ArrayList containing the documents to update | +| `options` |
UpdateOptions

(`null`) | Query options | + +--- + +### documents + +Each document has the following properties: + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `_id` |
String
| Document ID | +| `body` |
ConcurrentHashMap
| Document body | + +### options + +An [UpdateOptions](/sdk/java/3/core-classes/update-options) object. + +The `mUpdate` method takes into account those following arguments: + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `retryOnConflict` |
Integer
(optional) | The number of times the database layer should retry in case of version conflict | +| `waitForRefresh` |
Boolean
(optional) | If set to `true`, Kuzzle will wait for the persistence layer to finish indexing | + + +## Return + +A `ConcurrentHashMap>` which has a `successes` and `errors` `ArrayList`: +Each created document is an object of the `successes` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Updated document | +| `_id` |
String
| ID of the updated document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +Each errored document is an object of the `errors` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `document` |
ConcurrentHashMap
| Document that causes the error | +| `status` |
Integer
| HTTP error status | +| `reason` |
String
| Human readable reason | + +## Usage + +<<< ./snippets/m-update.java diff --git a/doc/3/controllers/document/m-update/snippets/m-update.java b/doc/3/controllers/document/m-update/snippets/m-update.java new file mode 100644 index 00000000..3e271495 --- /dev/null +++ b/doc/3/controllers/document/m-update/snippets/m-update.java @@ -0,0 +1,54 @@ +ConcurrentHashMap document1 = new ConcurrentHashMap<>(); +ConcurrentHashMap document2 = new ConcurrentHashMap<>(); +ConcurrentHashMap body = new ConcurrentHashMap<>(); +ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + +body.put("name", "Smith"); +body2.put("name", "Freeman"); + +document1.put("_id", "some-id"); +document1.put("body", body); + +document2.put("_id", "some-id2"); +document2.put("body", body2); + +final ArrayList> documents = new ArrayList<>(); +documents.add(document1); +documents.add(document2); + +ConcurrentHashMap> result = kuzzle + .getDocumentController() + .mUpdate("nyc-open-data", "yellow-taxi", documents) + .get(); + +/* +result = + { + successes= + [ + { + result=created, + _source= + { + Agent=Smith, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id, + _version=1, + status=200 + }, + { + result=created, + _source= + { + Gordon=Freeman, + _kuzzle_info={createdAt=1582892842099, author=-1} + }, + _id=some-id2, + _version=1, + status=200 + } + ], + errors=[] + } +*/ diff --git a/doc/3/controllers/document/m-update/snippets/m-update.test.yml b/doc/3/controllers/document/m-update/snippets/m-update.test.yml new file mode 100644 index 00000000..b14ef60a --- /dev/null +++ b/doc/3/controllers/document/m-update/snippets/m-update.test.yml @@ -0,0 +1,14 @@ +name: document#mUpdate +description: Updates multiple documents +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"name":"John"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + curl -XPOST -d '{"name":"John"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id2/_create + after: +template: print-result-array +expected: + - "id=some-id, _version=2, status=200" + - "id=some-id2, _version=2, status=200" \ No newline at end of file diff --git a/doc/3/controllers/document/replace/index.md b/doc/3/controllers/document/replace/index.md new file mode 100644 index 00000000..fc3bb906 --- /dev/null +++ b/doc/3/controllers/document/replace/index.md @@ -0,0 +1,55 @@ +--- +code: true +type: page +title: replace +description: Replaces a document +--- + +# replace + +Replaces the content of an existing document. + +--- + +## Arguments + +```java +public CompletableFuture> replace( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document) +throws NotConnectedException, InternalException + +public CompletableFuture> replace( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document, + final Boolean waitForRefresh) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `id` |
String
| Document ID | +| `document` |
ConcurrentHashMap
| New content of the document to update | +| `waitForRefresh` |
Boolean
| If set to `true`, Kuzzle will wait for the persistence layer to finish indexing| + +--- + +## Return + +A `ConcurrentHashMap` which has the following properties: + +| Property | Type | Description | +|------------- |----------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Document content | +| `_id` |
String
| ID of the document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +## Usage + +<<< ./snippets/replace.java diff --git a/doc/3/controllers/document/replace/snippets/replace.java b/doc/3/controllers/document/replace/snippets/replace.java new file mode 100644 index 00000000..68c90c11 --- /dev/null +++ b/doc/3/controllers/document/replace/snippets/replace.java @@ -0,0 +1,19 @@ + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("firstname", "John"); + + ConcurrentHashMap result = kuzzle.getDocumentController().replace("nyc-open-data", "yellow-taxi", "some-id", document) + .get(); + + /* + result = + { + _source= + { + firstname=John, + _kuzzle_info={ createdAt=1582892606555, author=-1, updatedAt=1582892606555, updater=-1 } + }, + _id=some-id, + _version=2 + } + */ \ No newline at end of file diff --git a/doc/3/controllers/document/replace/snippets/replace.test.yml b/doc/3/controllers/document/replace/snippets/replace.test.yml new file mode 100644 index 00000000..4b53e0ba --- /dev/null +++ b/doc/3/controllers/document/replace/snippets/replace.test.yml @@ -0,0 +1,11 @@ +name: document#replace +description: replaces a document +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + after: +template: print-result +expected: "firstname=John" \ No newline at end of file diff --git a/doc/3/controllers/document/search/index.md b/doc/3/controllers/document/search/index.md new file mode 100644 index 00000000..be93d933 --- /dev/null +++ b/doc/3/controllers/document/search/index.md @@ -0,0 +1,78 @@ +--- +code: true +type: page +title: search +description: Searches a document +--- + +# search + +Searches document. + +::: warning +There is a limit to how many documents can be returned by a single search query. +That limit is by default set at 10000 documents, and you can't get over it even with the from and size pagination options. +::: + +::: info +When processing a large number of documents (i.e. more than 1000), it is advised to paginate the results using [SearchResult.next](/sdk/java/3/core-classes/search-result/next) rather than increasing the size parameter. +::: + +::: warning +When using a cursor with the `scroll` option, Elasticsearch has to duplicate the transaction log to keep the same result during the entire scroll session. +It can lead to memory leaks if a scroll duration too great is provided, or if too many scroll sessions are open simultaneously. +::: + +::: info + +You can restrict the scroll session maximum duration under the `services.storage.maxScrollDuration` configuration key. +::: + +--- + +## Arguments + +```java +public CompletableFuture search( + final String index, + final String collection, + final ConcurrentHashMap searchQuery, + final SearchOptions options) throws NotConnectedException, InternalException + +``` + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `searchQuery` |
ConcurrentHashMap
| Search query | +| `options` |
SearchOptions
| Query options | +--- + +### searchQuery body properties: + +- `query`: the search query itself, using the [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/7.3/query-dsl.html) syntax. +- `aggregations`: control how the search results should be [aggregated](https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-aggregations.html) +- `sort`: contains a list of fields, used to [sort search results](https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-request-sort.html), in order of importance. + +An empty body matches all documents in the queried collection. + +### options + +A [SearchOptions](/sdk/java/3/core-classes/search-options) object. + +The following options can be set: + +| Options | Type
(default) | Description | +| ---------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `from` |
Integer

(`0`) | Offset of the first document to fetch | +| `size` |
Integer

(`10`) | Maximum number of documents to retrieve per page | +| `scroll` |
String

(`""`) | When set, gets a forward-only cursor having its ttl set to the given value (ie `1s`; cf [elasticsearch time limits](https://www.elastic.co/guide/en/elasticsearch/reference/7.3/common-options.html#time-units)) | + +## Return + +Returns a [SearchResult](/sdk/java/3/core-classes/search-result) object. + +## Usage + +<<< ./snippets/search.java diff --git a/doc/3/controllers/document/search/snippets/search.java b/doc/3/controllers/document/search/snippets/search.java new file mode 100644 index 00000000..5e7c5162 --- /dev/null +++ b/doc/3/controllers/document/search/snippets/search.java @@ -0,0 +1,53 @@ + ConcurrentHashMap suv = new ConcurrentHashMap<>(); + suv.put("category", "suv"); + ConcurrentHashMap limousine = new ConcurrentHashMap<>(); + limousine.put("category", "limousine"); + + CreateOptions options = new CreateOptions(); + options.setWaitForRefresh(true); + + for (int i = 0; i < 5; i += 1) { + kuzzle.getDocumentController().create("nyc-open-data", "yellow-taxi", suv, options).get(); + } + + for (int i = 0; i < 10; i += 1) { + kuzzle.getDocumentController().create("nyc-open-data", "yellow-taxi", limousine, options).get(); + } + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("category", "suv"); + query.put("match", match); + searchQuery.put("query", query); + + SearchResult results = kuzzle + .getDocumentController() + .search("nyc-open-data", "yellow-taxi", searchQuery).get(); + + System.out.println("Successfully retrieved " + results.total + " documents"); + + /* + { + "aggregations"=undefined, + "hits"=[ + { + "_id"="AWgi6A1POQUM6ucJ3q06", + "_score"=0.046520017, + "_source"={ + "category"="suv", + "_kuzzle_info"={ + "author"="-1", + "createdAt"=1546773859655, + "updatedAt"=null, + "updater"=null + } + } + }, + ... + ] + }, + "total"=5, + "fetched"=5, + "scroll_id"=undefined + */ \ No newline at end of file diff --git a/doc/3/controllers/document/search/snippets/search.test.yml b/doc/3/controllers/document/search/snippets/search.test.yml new file mode 100644 index 00000000..bddfd667 --- /dev/null +++ b/doc/3/controllers/document/search/snippets/search.test.yml @@ -0,0 +1,10 @@ +name: document#search +description: Search for documents +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: default +expected: Successfully retrieved 5 documents \ No newline at end of file diff --git a/doc/3/controllers/document/update-by-query/index.md b/doc/3/controllers/document/update-by-query/index.md new file mode 100644 index 00000000..09f0d8b0 --- /dev/null +++ b/doc/3/controllers/document/update-by-query/index.md @@ -0,0 +1,76 @@ +--- +code: true +type: page +title: updateByQuery +description: Updates documents matching query +--- + +# updateByQuery + +Updates documents matching the provided search query. + +Kuzzle uses the [ElasticSearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl.html) syntax. + +An empty or null query will match all documents in the collection. + +
+ +```java + public CompletableFuture>> updateByQuery( + final String index, + final String collection, + final ConcurrentHashMap searchQuery, + final ConcurrentHashMap changes) throws NotConnectedException, InternalException + + public CompletableFuture>> updateByQuery( + final String index, + final String collection, + final ConcurrentHashMap searchQuery, + final ConcurrentHashMap changes, + final UpdateOptions options) throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +| ------------------ | -------------------------------------------- | --------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `searchQuery` |
ConcurrentHashMap
| Query to match | +| `changes` |
ConcurrentHashMap
| Partial changes to apply to the documents | +| `options` |
UpdateOptions

(`null`) | Optional parameters | + +--- + +### options + +A [UpdateOptions](/sdk/java/3/core-classes/update-options) object. + +The following options can be set: + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `waitForRefresh` |
Boolean
| If set to `true`, Kuzzle will wait for the persistence layer to finish indexing| +| `source` |
Boolean
| If true, returns the updated document inside the response | + +## Returns + +A `ConcurrentHashMap>` which has a `successes` and `errors` `ArrayList`: +Each updated document is an object of the `successes` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `_source` |
ConcurrentHashMap
| Updated document (if `source` option set to true) | +| `_id` |
String
| ID of the udated document | +| `_version` |
Integer
| Version of the document in the persistent data storage | +| `status` |
Integer
| HTTP status code | + +Each errored document is an object of the `errors` array with the following properties: + +| Property | Type | Description | +|------------- |--------------------------------------------- |--------------------------------- | +| `document` |
ConcurrentHashMap
| Document that causes the error | +| `status` |
Integer
| HTTP error status | +| `reason` |
String
| Human readable reason | + +## Usage + +<<< ./snippets/update-by-query.js \ No newline at end of file diff --git a/doc/3/controllers/document/update-by-query/snippets/update-by-query.java b/doc/3/controllers/document/update-by-query/snippets/update-by-query.java new file mode 100644 index 00000000..e8939278 --- /dev/null +++ b/doc/3/controllers/document/update-by-query/snippets/update-by-query.java @@ -0,0 +1,30 @@ + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("capacity", 4); + searchQuery.put("match", match); + + ConcurrentHashMap changes = new ConcurrentHashMap<>(); + changes.put("capacity", 42); + + ConcurrentHashMap> result = kuzzle + .getDocumentController() + .updateByQuery("nyc-open-data", "yellow-taxi", searchQuery, changes) + .get(); + + /* + { + successes=[ + { + _id=, + _source= // if source set to true + status=200 + }, + { + _id=, + _source= // if source set to true + status=200 + } + ], + errors=[] + } + */ \ No newline at end of file diff --git a/doc/3/controllers/document/update-by-query/snippets/update-by-query.test.yml b/doc/3/controllers/document/update-by-query/snippets/update-by-query.test.yml new file mode 100644 index 00000000..5473fced --- /dev/null +++ b/doc/3/controllers/document/update-by-query/snippets/update-by-query.test.yml @@ -0,0 +1,19 @@ +name: document#updateByQuery +description: Update documents matching query +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + for i in 1 2 ; do + curl -H "Content-type: application/json" -d '{"capacity": 4}' kuzzle:7512/nyc-open-data/yellow-taxi/document_$i/_create + done + for i in 1 2 3 4 5; do + curl -H "Content-type: application/json" -d '{"capacity": 7}' kuzzle:7512/nyc-open-data/yellow-taxi/_create + done + curl -XPOST kuzzle:7512/nyc-open-data/_refresh + after: +template: print-result-array +expected: + - "id=document_1, _version=2, status=200" + - "id=document_2, _version=2, status=200" \ No newline at end of file diff --git a/doc/3/controllers/document/update/index.md b/doc/3/controllers/document/update/index.md new file mode 100644 index 00000000..35f59888 --- /dev/null +++ b/doc/3/controllers/document/update/index.md @@ -0,0 +1,67 @@ +--- +code: true +type: page +title: update +description: Updates a document +--- + +# update + +Updates a document. + +--- + +## Arguments + +```java +public CompletableFuture> update( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document) +throws NotConnectedException, InternalException + +public CompletableFuture> update( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document, + final UpdateOptions options) +throws NotConnectedException, InternalException +``` + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `index` |
String
| Index | +| `collection` |
String
| Collection | +| `id ` |
String
| Document ID | +| `document` |
ConcurrentHashMap
| Partial document content | +| `options` |
UpdateOptions

(`null`) | Optional parameters | + +--- + +### options + +A [UpdateOptions](/sdk/java/3/core-classes/update-options) object. + +The following options can be set: + +| Arguments | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | | +| `waitForRefresh` |
Boolean
| If set to `true`, Kuzzle will wait for the persistence layer to finish indexing| +| `retryOnConflict` |
Integer
| The number of times the database layer should retry in case of version conflict | +| `source` |
Boolean
| If true, returns the updated document inside the response | + +## Return + +A `ConcurrentHashMap` which has the following properties: + +| Property | Type | Description | +|------------- |----------------------------- |--------------------------------------------------------------- | +| `_source` |
ConcurrentHashMap
| Updated document (If source option set to true) | +| `_id` |
String
| ID of the updated document | +| `_version` |
Integer
| Version of the document in the persistent data storage | + +## Usage + +<<< ./snippets/update.java diff --git a/doc/3/controllers/document/update/snippets/update.java b/doc/3/controllers/document/update/snippets/update.java new file mode 100644 index 00000000..ead423c8 --- /dev/null +++ b/doc/3/controllers/document/update/snippets/update.java @@ -0,0 +1,14 @@ + ConcurrentHashMap content = new ConcurrentHashMap<>(); + content.put("name", "Johny"); + + ConcurrentHashMap result = + kuzzle.getDocumentController().update("nyc-open-data", "yellow-taxi", "some-id", content) + .get(); + +/* + response = + { + _id=some-id, + _version=2 + } +*/ \ No newline at end of file diff --git a/doc/3/controllers/document/update/snippets/update.test.yml b/doc/3/controllers/document/update/snippets/update.test.yml new file mode 100644 index 00000000..f16f3719 --- /dev/null +++ b/doc/3/controllers/document/update/snippets/update.test.yml @@ -0,0 +1,11 @@ +name: document#update +description: Update a document +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -XPOST -d '{"name":"John"}' -H "Content-Type: application/json" kuzzle:7512/nyc-open-data/yellow-taxi/some-id/_create + after: +template: print-result +expected: "{_id=some-id, _version=2}" \ No newline at end of file diff --git a/doc/3/controllers/document/validate/index.md b/doc/3/controllers/document/validate/index.md new file mode 100644 index 00000000..3ad5249d --- /dev/null +++ b/doc/3/controllers/document/validate/index.md @@ -0,0 +1,38 @@ +--- +code: true +type: page +title: validate +description: Validate a document +--- + +# validate + +Validates data against existing validation rules. + +Note that if no validation specifications are set for the ``/``, the document will always be valid. + +This request does **not** store or publish the document. + +
+ +```java +public CompletableFuture validate( + final String index, + final String collection, + final ConcurrentHashMap document) +throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +| ------------ | -------------------------------------------- | -------------------- | +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `document` |
ConcurrentHashMap
| Document to validate | + +## Returns + +Returns a boolean value set to true if the document is valid and false otherwise. + +## Usage + +<<< ./snippets/validate.java \ No newline at end of file diff --git a/doc/3/controllers/document/validate/snippets/validate.java b/doc/3/controllers/document/validate/snippets/validate.java new file mode 100644 index 00000000..aaad866e --- /dev/null +++ b/doc/3/controllers/document/validate/snippets/validate.java @@ -0,0 +1,7 @@ + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("key", "value"); + + Boolean result = kuzzle + .getDocumentController() + .validate("nyc-open-data", "yellow-taxi", document) + .get(); diff --git a/doc/3/controllers/document/validate/snippets/validate.test.yml b/doc/3/controllers/document/validate/snippets/validate.test.yml new file mode 100644 index 00000000..63717fd0 --- /dev/null +++ b/doc/3/controllers/document/validate/snippets/validate.test.yml @@ -0,0 +1,10 @@ +name: document#validate +description: Validates a document +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: +template: print-result +expected: true \ No newline at end of file diff --git a/doc/3/controllers/index.md b/doc/3/controllers/index.md new file mode 100644 index 00000000..3e88f493 --- /dev/null +++ b/doc/3/controllers/index.md @@ -0,0 +1,7 @@ +--- +code: false +type: branch +order: 60 +title: Controllers +description: Kuzzle Java SDK controllers +--- diff --git a/doc/3/controllers/index/create/index.md b/doc/3/controllers/index/create/index.md new file mode 100644 index 00000000..8f4d03d6 --- /dev/null +++ b/doc/3/controllers/index/create/index.md @@ -0,0 +1,25 @@ +--- +code: true +type: page +title: create +description: Creates an index. +--- + +# create + +Creates a new index in Kuzzle + +## Arguments + +```java +CompletableFuture create(final String index) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|----------|-------------------|-------------| +| `index` |
String
| Index name | + +## Usage + +<<< ./snippets/create.java diff --git a/doc/3/controllers/index/create/snippets/create.java b/doc/3/controllers/index/create/snippets/create.java new file mode 100644 index 00000000..5fa80ccf --- /dev/null +++ b/doc/3/controllers/index/create/snippets/create.java @@ -0,0 +1 @@ +kuzzle.getIndexController().create("nyc-open-data").get(); diff --git a/doc/3/controllers/index/create/snippets/create.test.yml b/doc/3/controllers/index/create/snippets/create.test.yml new file mode 100644 index 00000000..dd0311dc --- /dev/null +++ b/doc/3/controllers/index/create/snippets/create.test.yml @@ -0,0 +1,8 @@ +--- +name: Index#CreateAsync +description: Creates a new index. +hooks: + before: curl -X DELETE kuzzle:7512/nyc-open-data + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/index/delete/index.md b/doc/3/controllers/index/delete/index.md new file mode 100644 index 00000000..821b3603 --- /dev/null +++ b/doc/3/controllers/index/delete/index.md @@ -0,0 +1,25 @@ +--- +code: true +type: page +title: delete +description: Deletes an index. +--- + +# delete + +Deletes an entire index from Kuzzle. + +## Arguments + +```java +CompletableFuture delete(final String index) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|----------|-------------------|-------------| +| `index` |
String
| Index name | + +## Usage + +<<< ./snippets/delete.java diff --git a/doc/3/controllers/index/delete/snippets/delete.java b/doc/3/controllers/index/delete/snippets/delete.java new file mode 100644 index 00000000..b126d403 --- /dev/null +++ b/doc/3/controllers/index/delete/snippets/delete.java @@ -0,0 +1 @@ +kuzzle.getIndexController().delete("nyc-open-data").get(); diff --git a/doc/3/controllers/index/delete/snippets/delete.test.yml b/doc/3/controllers/index/delete/snippets/delete.test.yml new file mode 100644 index 00000000..5f055e24 --- /dev/null +++ b/doc/3/controllers/index/delete/snippets/delete.test.yml @@ -0,0 +1,8 @@ +--- +name: Index#Delete +description: Delete an index. +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/index/exists/index.md b/doc/3/controllers/index/exists/index.md new file mode 100644 index 00000000..69e9c014 --- /dev/null +++ b/doc/3/controllers/index/exists/index.md @@ -0,0 +1,29 @@ +--- +code: true +type: page +title: exists +description: Check for index existence. +--- + +# exists + +Checks if the given index exists in Kuzzle. + +## Arguments + +```java +CompletableFuture exists(final String index) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|----------|-------------------|-------------| +| `index` |
String
| Index name | + +## Return + +Returns a `boolean` that indicates whether the index exists or not. + +## Usage + +<<< ./snippets/exists.java diff --git a/doc/3/controllers/index/exists/snippets/exists.java b/doc/3/controllers/index/exists/snippets/exists.java new file mode 100644 index 00000000..557cb953 --- /dev/null +++ b/doc/3/controllers/index/exists/snippets/exists.java @@ -0,0 +1 @@ +Boolean result = kuzzle.getIndexController().exists("nyc-open-data").get(); diff --git a/doc/3/controllers/index/exists/snippets/exists.test.yml b/doc/3/controllers/index/exists/snippets/exists.test.yml new file mode 100644 index 00000000..d32f6f3a --- /dev/null +++ b/doc/3/controllers/index/exists/snippets/exists.test.yml @@ -0,0 +1,8 @@ +--- +name: Index#ExistsAsync +description: Test if an index exists. +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create + after: +template: print-result +expected: true \ No newline at end of file diff --git a/doc/3/controllers/index/index.md b/doc/3/controllers/index/index.md new file mode 100644 index 00000000..8d74e9c0 --- /dev/null +++ b/doc/3/controllers/index/index.md @@ -0,0 +1,8 @@ +--- +code: true +type: branch +title: Index +description: Index Controller +--- + +# Index Controller diff --git a/doc/3/controllers/index/list/index.md b/doc/3/controllers/index/list/index.md new file mode 100644 index 00000000..ddf5ee86 --- /dev/null +++ b/doc/3/controllers/index/list/index.md @@ -0,0 +1,25 @@ +--- +code: true +type: page +title: list +description: Lists the indexes. +--- + +# list + +Gets the complete list of indexes handled by Kuzzle. + +## Arguments + +```java +CompletableFuture> list() + throws NotConnectedException, InternalException +``` + +## Return + +Returns an `ArrayList` containing the list of index names handled by Kuzzle. + +## Usage + +<<< ./snippets/list.java diff --git a/doc/3/controllers/index/list/snippets/list.java b/doc/3/controllers/index/list/snippets/list.java new file mode 100644 index 00000000..eb4c1cc4 --- /dev/null +++ b/doc/3/controllers/index/list/snippets/list.java @@ -0,0 +1 @@ +ArrayList result = kuzzle.getIndexController().list().get(); diff --git a/doc/3/controllers/index/list/snippets/list.test.yml b/doc/3/controllers/index/list/snippets/list.test.yml new file mode 100644 index 00000000..4c703391 --- /dev/null +++ b/doc/3/controllers/index/list/snippets/list.test.yml @@ -0,0 +1,10 @@ +--- +name: Index#ListAsync +description: List indexes handled by Kuzzle. +hooks: + before: | + curl -X POST kuzzle:7512/admin/_resetDatabase + curl -X POST kuzzle:7512/nyc-open-data/_create + after: +template: print-result +expected: ["nyc-open-data"] diff --git a/doc/3/controllers/index/m-delete/index.md b/doc/3/controllers/index/m-delete/index.md new file mode 100644 index 00000000..212edebc --- /dev/null +++ b/doc/3/controllers/index/m-delete/index.md @@ -0,0 +1,29 @@ +--- +code: true +type: page +title: mDelete +description: Deletes multiple indexes. +--- + +# mDelete + +Deletes multiple indexes. + +## Arguments + +```java +CompletableFuture> mDelete(final ArrayList indexes) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|-----------|-------------------|-----------------------| +| `indexes` |
ArrayList
| List of indexes names | + +## Return + +Returns an `ArrayList` containing the list of indexes names deleted. + +## Usage + +<<< ./snippets/mDelete.java diff --git a/doc/3/controllers/index/m-delete/snippets/mDelete.java b/doc/3/controllers/index/m-delete/snippets/mDelete.java new file mode 100644 index 00000000..9ac9c0be --- /dev/null +++ b/doc/3/controllers/index/m-delete/snippets/mDelete.java @@ -0,0 +1,3 @@ +ArrayList indexes = new ArrayList<>(); + indexes.add("nyc-open-data"); +ArrayList result = kuzzle.getIndexController().mDelete(indexes).get(); diff --git a/doc/3/controllers/index/m-delete/snippets/mDelete.test.yml b/doc/3/controllers/index/m-delete/snippets/mDelete.test.yml new file mode 100644 index 00000000..00423931 --- /dev/null +++ b/doc/3/controllers/index/m-delete/snippets/mDelete.test.yml @@ -0,0 +1,8 @@ +--- +name: Index#MDeleteAsync +description: Delete multiple indexes. +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create ; curl -X POST kuzzle:7512/mtp-open-data/_create + after: +template: print-result +expected: ["nyc-open-data"] \ No newline at end of file diff --git a/doc/3/controllers/realtime/count/index.md b/doc/3/controllers/realtime/count/index.md new file mode 100644 index 00000000..36066ea6 --- /dev/null +++ b/doc/3/controllers/realtime/count/index.md @@ -0,0 +1,29 @@ +--- +code: true +type: page +title: count +description: Returns the number of other connections sharing the same subscription. +--- + +# count + +Returns the number of other connections sharing the same subscription. + +## Arguments + +```java +public CompletableFuture count(final String roomId) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|-----------|-------------------|----------------------| +| `room_id` |
String
| Subscription room ID | + +## Return + +Returns the number of active connections using the same provided subscription room. + +## Usage + +<<< ./snippets/count.java diff --git a/doc/3/controllers/realtime/count/snippets/count.java b/doc/3/controllers/realtime/count/snippets/count.java new file mode 100644 index 00000000..f5748e60 --- /dev/null +++ b/doc/3/controllers/realtime/count/snippets/count.java @@ -0,0 +1,22 @@ +SubscribeOptions options = new SubscribeOptions(); +options.setSubscribeToSelf(true); + +ConcurrentHashMap filters = new ConcurrentHashMap<>(); +filters.put("exists", "name"); + +ConcurrentHashMap document = new ConcurrentHashMap<>(); +document.put("name", "nina-vkote"); + +final String roomId = kuzzle.getRealtimeController().subscribe( + "nyc-open-data", + "yellow-taxi", + filters, + notification -> { + if (notification.scope.equals(SubscribeOptions.Scope.IN.toString())) { + System.out.println("Document entered the scope"); + } else { + System.out.println("Document left the scope"); + } +}).get(); + +final Integer result = kuzzle.getRealtimeController().count(roomId).get(); \ No newline at end of file diff --git a/doc/3/controllers/realtime/count/snippets/count.test.yml b/doc/3/controllers/realtime/count/snippets/count.test.yml new file mode 100644 index 00000000..0392ea47 --- /dev/null +++ b/doc/3/controllers/realtime/count/snippets/count.test.yml @@ -0,0 +1,7 @@ +name: Realtime#count +description: Counts subscribers for a subscription room. +hooks: + before: + after: +template: print-result +expected: 1 \ No newline at end of file diff --git a/doc/3/controllers/realtime/index.md b/doc/3/controllers/realtime/index.md new file mode 100644 index 00000000..0609f3b0 --- /dev/null +++ b/doc/3/controllers/realtime/index.md @@ -0,0 +1,8 @@ +--- +code: true +type: branch +title: Realtime +description: Realtime Controller +--- + +# Realtime Controller diff --git a/doc/3/controllers/realtime/publish/index.md b/doc/3/controllers/realtime/publish/index.md new file mode 100644 index 00000000..9df4a740 --- /dev/null +++ b/doc/3/controllers/realtime/publish/index.md @@ -0,0 +1,34 @@ +--- +code: true +type: page +title: publish +description: Publishes a real-time message. +--- + +# publish + +Sends a real-time message to Kuzzle. The message will be broadcasted to all clients with subscriptions matching the index, the collection and the message content. + +The index and collection are indicative and serve only to distinguish the rooms. They are not required to exist in the database. + +**Note:** real-time messages are not persisted in the database. + +## Arguments + +```java +public CompletableFuture publish( + final String index, + final String collection, + final ConcurrentHashMap message) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|--------------|--------------------|-------------------------------------| +| `index` |
String
| Index name | +| `collection` |
String
| Collection name | +| `message` |
ConcurrentHashMap
| ConcurrentHashMap representing a JSON payload | + +## Usage + +<<< ./snippets/publish.java diff --git a/doc/3/controllers/realtime/publish/snippets/publish.java b/doc/3/controllers/realtime/publish/snippets/publish.java new file mode 100644 index 00000000..db209db1 --- /dev/null +++ b/doc/3/controllers/realtime/publish/snippets/publish.java @@ -0,0 +1,4 @@ +ConcurrentHashMap document = new ConcurrentHashMap<>(); +document.put("name", "nina-vkote"); + +kuzzle.getRealtimeController().publish("my-index", "my-collection", document); \ No newline at end of file diff --git a/doc/3/controllers/realtime/publish/snippets/publish.test.yml b/doc/3/controllers/realtime/publish/snippets/publish.test.yml new file mode 100644 index 00000000..579119b6 --- /dev/null +++ b/doc/3/controllers/realtime/publish/snippets/publish.test.yml @@ -0,0 +1,7 @@ +name: Realtime#publish +description: Publishes a realtime message. +hooks: + before: + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/controllers/realtime/subscribe/index.md b/doc/3/controllers/realtime/subscribe/index.md new file mode 100644 index 00000000..0a487307 --- /dev/null +++ b/doc/3/controllers/realtime/subscribe/index.md @@ -0,0 +1,53 @@ +--- +code: true +type: page +title: subscribe +description: Subscribes to real-time notifications. +--- + +# Subscribe + +Subscribes by providing a set of filters: messages, document changes and, optionally, user events matching the provided filters will generate [real-time notifications](/core/2/api/essentials/notifications), sent to you in real-time by Kuzzle. + +## Arguments + +```java +public CompletableFuture subscribe( + final String index, + final String collection, + final ConcurrentHashMap filters, + final NotificationHandler handler, + final SubscribeOptions options +) throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|--------------|-----------------------------------------|----------------------------------------------------------------------------------------------------------------| +| `index` |
String/pre>                       | Index name                                                                                                     |
+| `collection` | 
String
| Collection name | +| `filters` |
ConcurrentHashMap
| ConcurrentHashMap representing a set of filters following [Koncorde syntax](/core/2/guides/cookbooks/realtime-api/terms) | +| `handler` |
NotificationHandler
| Handler function to handle notifications | +| `options` |
SubscribeOptions

(`null`) | Subscription options | + +### handler + +Handler function that will be called each time a new notification is received. +The hanlder will receive a [Response](/sdk/java/3/essentials/realtime-notifications) as its only argument. + +### options + +A [SubscribeOptions](/sdk/java/3/core-classes/subscribe-options) object. + +## Return + +The room ID. + +## Usage + +_Simple subscription to document notifications_ + +<<< ./snippets/document-notifications.java + +_Subscription to document notifications with scope option_ + +<<< ./snippets/document-notifications-leave-scope.java diff --git a/doc/3/controllers/realtime/subscribe/snippets/document-notifications-leave-scope.java b/doc/3/controllers/realtime/subscribe/snippets/document-notifications-leave-scope.java new file mode 100644 index 00000000..ad787914 --- /dev/null +++ b/doc/3/controllers/realtime/subscribe/snippets/document-notifications-leave-scope.java @@ -0,0 +1,38 @@ +SubscribeOptions options = new SubscribeOptions(); +options.setSubscribeToSelf(true); +options.setScope(SubscribeOptions.Scope.ALL); + +ConcurrentHashMap filters = new ConcurrentHashMap<>(); +ConcurrentHashMap range = new ConcurrentHashMap<>(); +ConcurrentHashMap age = new ConcurrentHashMap<>(); + +age.put("lte", 20); +range.put("age", age); +filters.put("range", range); + +kuzzle.getRealtimeController().subscribe( + "nyc-open-data", + "yellow-taxi", + filters, + notification -> { + if (notification.scope.equals(SubscribeOptions.Scope.OUT.toString())) { + System.out.println("Document left the scope"); + } else { + System.out.println("Document moved in the scope"); + } + }, options).get(); + +ConcurrentHashMap document = new ConcurrentHashMap<>(); +document.put("age", 19); +ConcurrentHashMap query = new ConcurrentHashMap<>(); +query.put("controller", "document"); +query.put("action", "create"); +query.put("index", "nyc-open-data"); +query.put("collection", "yellow-taxi"); +query.put("_id", "nina-vkote"); +query.put("body", document); +kuzzle.query(query).get(); + +query.put("action", "update"); +document.put("age", 42); +kuzzle.query(query).get(); \ No newline at end of file diff --git a/doc/3/controllers/realtime/subscribe/snippets/document-notifications-leave-scope.test.yml b/doc/3/controllers/realtime/subscribe/snippets/document-notifications-leave-scope.test.yml new file mode 100644 index 00000000..23670860 --- /dev/null +++ b/doc/3/controllers/realtime/subscribe/snippets/document-notifications-leave-scope.test.yml @@ -0,0 +1,10 @@ +name: Realtime#Subscribe-documents-leave-scope +description: Subscribes to documents leaving the scope. +hooks: + before: | + curl -X POST kuzzle:7512/nyc-open-data/_create + curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi/ + curl -X DELETE kuzzle:7512/nyc-open-data/yellow-taxi/nina-vkote + after: +template: default +expected: Document\ moved\ in\ the\ scope \ No newline at end of file diff --git a/doc/3/controllers/realtime/subscribe/snippets/document-notifications.java b/doc/3/controllers/realtime/subscribe/snippets/document-notifications.java new file mode 100644 index 00000000..b7b5573e --- /dev/null +++ b/doc/3/controllers/realtime/subscribe/snippets/document-notifications.java @@ -0,0 +1,29 @@ +SubscribeOptions options = new SubscribeOptions(); +options.setSubscribeToSelf(true); + +ConcurrentHashMap filters = new ConcurrentHashMap<>(); +filters.put("exists", "name"); + +ConcurrentHashMap document = new ConcurrentHashMap<>(); +document.put("name", "nina-vkote"); + +kuzzle.getRealtimeController().subscribe( +"nyc-open-data", +"yellow-taxi", +filters, +notification -> { + if (notification.scope.equals(SubscribeOptions.Scope.IN.toString())) { + System.out.println("Document entered the scope"); + } else { + System.out.println("Document left the scope"); + } +}).get(); + +ConcurrentHashMap query = new ConcurrentHashMap<>(); +query.put("controller", "document"); +query.put("action", "create"); +query.put("index", "nyc-open-data"); +query.put("collection", "yellow-taxi"); +query.put("_id", "nina-vkote"); +query.put("body", document); +kuzzle.query(query).get(); \ No newline at end of file diff --git a/doc/3/controllers/realtime/subscribe/snippets/document-notifications.test.yml b/doc/3/controllers/realtime/subscribe/snippets/document-notifications.test.yml new file mode 100644 index 00000000..ae39d8d5 --- /dev/null +++ b/doc/3/controllers/realtime/subscribe/snippets/document-notifications.test.yml @@ -0,0 +1,10 @@ +name: Realtime#Subscribe-documents +description: Subscribes to document notifications. +hooks: + before: | + curl -X POST kuzzle:7512/nyc-open-data/_create + curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi/ + curl -X DELETE kuzzle:7512/nyc-open-data/yellow-taxi/nina-vkote + after: +template: default +expected: Document entered the scope \ No newline at end of file diff --git a/doc/3/controllers/realtime/unsubscribe/index.md b/doc/3/controllers/realtime/unsubscribe/index.md new file mode 100644 index 00000000..aeb14d05 --- /dev/null +++ b/doc/3/controllers/realtime/unsubscribe/index.md @@ -0,0 +1,25 @@ +--- +code: true +type: page +title: unsubscribe +description: Removes a subscription. +--- + +# unsubscribe + +Removes a subscription. + +## Arguments + +```java +public CompletableFuture unsubscribe(final String roomId) + throws NotConnectedException, InternalException +``` + +| Argument | Type | Description | +|-----------|--------------------|----------------------| +| `room_id` |
String
| Subscription room ID | + +## Usage + +<<< ./snippets/unsubscribe.java diff --git a/doc/3/controllers/realtime/unsubscribe/snippets/unsubscribe.java b/doc/3/controllers/realtime/unsubscribe/snippets/unsubscribe.java new file mode 100644 index 00000000..8efafdba --- /dev/null +++ b/doc/3/controllers/realtime/unsubscribe/snippets/unsubscribe.java @@ -0,0 +1,22 @@ +SubscribeOptions options = new SubscribeOptions(); +options.setSubscribeToSelf(true); + +ConcurrentHashMap filters = new ConcurrentHashMap<>(); +filters.put("exists", "name"); + +ConcurrentHashMap document = new ConcurrentHashMap<>(); +document.put("name", "nina-vkote"); + +final String roomId = kuzzle.getRealtimeController().subscribe( + "nyc-open-data", + "yellow-taxi", + filters, + notification -> { + if (notification.scope.equals(SubscribeOptions.Scope.IN.toString())) { + System.out.println("Document entered the scope"); + } else { + System.out.println("Document left the scope"); + } +}).get(); + +kuzzle.getRealtimeController().unsubscribe(roomId).get(); \ No newline at end of file diff --git a/doc/3/controllers/realtime/unsubscribe/snippets/unsubscribe.test.yml b/doc/3/controllers/realtime/unsubscribe/snippets/unsubscribe.test.yml new file mode 100644 index 00000000..909e8388 --- /dev/null +++ b/doc/3/controllers/realtime/unsubscribe/snippets/unsubscribe.test.yml @@ -0,0 +1,7 @@ +name: Realtime#unsubscribe +description: Removes a subscription. +hooks: + before: + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/core-classes/create-options/index.md b/doc/3/core-classes/create-options/index.md new file mode 100644 index 00000000..4380195f --- /dev/null +++ b/doc/3/core-classes/create-options/index.md @@ -0,0 +1,26 @@ +--- +code: true +type: page +title: CreateOptions +description: CreateOptions class documentation +order: 110 +--- + +# CreateOptions + +This class represents the options usable with the [`create`](/sdk/java/3/controllers/document/create) method of the [DocumentController](/sdk/java/3/controllers/document). + +## Namespace + +You must include the following package: + +```java +import io.kuzzle.sdk.Options.CreateOptions; +``` + +## Properties + +| Property | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `id` |
String
(optional) | Document identifier. Auto-generated if not specified | +| `waitForRefresh` |
Boolean
(optional) | If set to `true`, Kuzzle will wait for the persistence layer to finish indexing| diff --git a/doc/3/core-classes/error-response/index.md b/doc/3/core-classes/error-response/index.md new file mode 100644 index 00000000..bae90d65 --- /dev/null +++ b/doc/3/core-classes/error-response/index.md @@ -0,0 +1,7 @@ +--- +code: true +type: branch +title: ErrorResponse +description: ErrorResponse object documentation +order: 0 +--- \ No newline at end of file diff --git a/doc/3/core-classes/error-response/introduction/index.md b/doc/3/core-classes/error-response/introduction/index.md new file mode 100644 index 00000000..1e0cc386 --- /dev/null +++ b/doc/3/core-classes/error-response/introduction/index.md @@ -0,0 +1,20 @@ +--- +code: false +type: page +title: Introduction +description: ErrorResponse object description +order: 0 +--- + +## ErrorResponse + +`ErrorResponse` is a **serializable** class representing a raw Kuzzle response with error. + +## Properties + +| Property | Type | Description | +|--- |--- |--- | +| `id` |
String
| Error ID | +| `message` |
String
| Error message | +| `stack` |
String
| Error stack | +| `status` |
int
| esponse status, following HTTP status codes. | diff --git a/doc/3/core-classes/index.md b/doc/3/core-classes/index.md new file mode 100644 index 00000000..5f2b6b45 --- /dev/null +++ b/doc/3/core-classes/index.md @@ -0,0 +1,7 @@ +--- +code: false +type: branch +order: 40 +title: Core classes +description: Kuzzle Java SDK core classes +--- diff --git a/doc/3/core-classes/kuzzle-options/index.md b/doc/3/core-classes/kuzzle-options/index.md new file mode 100644 index 00000000..8f7aa867 --- /dev/null +++ b/doc/3/core-classes/kuzzle-options/index.md @@ -0,0 +1,65 @@ +--- +code: true +type: page +title: KuzzleOptions +description: KuzzleOptions class documentation +order: 110 +--- + +# KuzzleOptions + +This class represents the options usable with the Kuzzle class. + +It can be used with the following methods: + - [Kuzzle.Kuzzle](/sdk/java/3/core-classes/kuzzle) + +# Constructor + +This class has a constructor and a constructor by copy. + +## Getters and setters + +### queueMaxSize + +The maximum amount of elements that the queue can contains. If set to -1, the size is unlimited. + +```java +public int getMaxQueueSize(); +public KuzzleOptions setMaxQueueSize(int maxQueueSize) +``` + +### minTokenDuration + +The minimum duration of a Token before being automatically refreshed. If set to -1 the SDK does not refresh the token automatically. + +```java +public int getMinTokenDuration() +public KuzzleOptions setMinTokenDuration(int minTokenDuration) +``` + +### refreshedTokenDuration + +The minimum duration of a Token after refresh. If set to -1 the SDK does not refresh the token automatically. + +```java +public int getRefreshedTokenDuration() +public KuzzleOptions setRefreshedTokenDuration(int refreshedTokenDuration) +``` + +### maxRequestDelay + +The maximum delay between two requests to be replayed. + +```java +public int getMaxRequestDelay() +public KuzzleOptions setMaxRequestDelay(int maxRequestDelay) +``` + +### autoResubscribe + +Automatically renew all subscriptions on a `reconnected` event. + +```java +public boolean isAutoResubscribe(); +public KuzzleOptions setAutoResubscribe(boolean autoResubscribe); +``` diff --git a/doc/3/core-classes/kuzzle/connect/index.md b/doc/3/core-classes/kuzzle/connect/index.md new file mode 100644 index 00000000..983d56c9 --- /dev/null +++ b/doc/3/core-classes/kuzzle/connect/index.md @@ -0,0 +1,22 @@ +--- +code: true +type: page +title: Connect +description: Connects the SDK to Kuzzle +--- + +# Connect + +Connects to Kuzzle using the underlying protocol `connect` method. + +Subsequent calls have no effect if the SDK is already connected. + +## Arguments + +```java +public void connect() throws Exception; +``` + +## Usage + +<<< ./snippets/connect.java diff --git a/doc/3/core-classes/kuzzle/connect/snippets/connect.java b/doc/3/core-classes/kuzzle/connect/snippets/connect.java new file mode 100644 index 00000000..599a215c --- /dev/null +++ b/doc/3/core-classes/kuzzle/connect/snippets/connect.java @@ -0,0 +1 @@ +kuzzle.connect(); diff --git a/doc/3/core-classes/kuzzle/connect/snippets/connect.test.yml b/doc/3/core-classes/kuzzle/connect/snippets/connect.test.yml new file mode 100644 index 00000000..9932ecd6 --- /dev/null +++ b/doc/3/core-classes/kuzzle/connect/snippets/connect.test.yml @@ -0,0 +1,8 @@ +--- +name: kuzzle#Connect +description: Connects the SDK to Kuzzle +hooks: + before: + after: +template: without-connect +expected: Success diff --git a/doc/3/core-classes/kuzzle/constructor/index.md b/doc/3/core-classes/kuzzle/constructor/index.md new file mode 100644 index 00000000..f2b2f5c8 --- /dev/null +++ b/doc/3/core-classes/kuzzle/constructor/index.md @@ -0,0 +1,52 @@ +--- +code: true +type: page +title: Constructor +description: Creates a new Kuzzle object connected to the backend +order: 100 +--- + +# Constructor + +Use this constructor to create a new instance of the SDK. +Each instance represents a different connection to a Kuzzle server with specific options. + +## Arguments + +```java +public Kuzzle( + AbstractProtocol networkProtocol, + KuzzleOptions options +) throws IllegalArgumentException +``` + +
+ +| Argument | Type | Description | +| ---------- | ------------------- | --------------------------------- | +| `networkProtocol` |
AbstractProtocol
| Protocol used by the SDK instance | +| `options` |
KuzzleOptions
| Class which contains options | + +## networkProtocol + +The protocol used to connect to the Kuzzle instance. +It can be one of the following available protocols: + +- [WebSocket](/sdk/java/3/protocols/websocket) + +## options + +The options used to connect to the Kuzzle instance. +[KuzzleOptions](/sdk/java/3/core-classes/kuzzle-options) + +## Return + +The `Kuzzle` SDK instance. + +## Throws + +Can throw an [IllegalArgumentException](/sdk/java/3/exceptions/illegal-argument-exception) + +## Usage + +<<< ./snippets/constructor.java diff --git a/doc/3/core-classes/kuzzle/constructor/snippets/constructor.java b/doc/3/core-classes/kuzzle/constructor/snippets/constructor.java new file mode 100644 index 00000000..279377aa --- /dev/null +++ b/doc/3/core-classes/kuzzle/constructor/snippets/constructor.java @@ -0,0 +1,7 @@ +KuzzleOptions options = new KuzzleOptions(); +options.setMaxQueueSize(42) + .setMaxRequestDelay(1) + .setMinTokenDuration(24) + .setRefreshedTokenDuration(40) + .setQueueFilter(stringObjectConcurrentHashMap -> true); +Kuzzle kuzzle = new Kuzzle(new WebSocket("kuzzle"), options); diff --git a/doc/3/core-classes/kuzzle/constructor/snippets/constructor.test.yml b/doc/3/core-classes/kuzzle/constructor/snippets/constructor.test.yml new file mode 100644 index 00000000..3ff0862d --- /dev/null +++ b/doc/3/core-classes/kuzzle/constructor/snippets/constructor.test.yml @@ -0,0 +1,8 @@ +--- +name: kuzzle#constructor +description: Creates a new Kuzzle instance +hooks: + before: + after: +template: without-ctor +expected: Success \ No newline at end of file diff --git a/doc/3/core-classes/kuzzle/disconnect/index.md b/doc/3/core-classes/kuzzle/disconnect/index.md new file mode 100644 index 00000000..1f4d7de8 --- /dev/null +++ b/doc/3/core-classes/kuzzle/disconnect/index.md @@ -0,0 +1,22 @@ +--- +code: true +type: page +title: Disconnect +description: Disconnects the SDK from Kuzzle +--- + +# Disconnect + +Closes the current connection to Kuzzle. + +Disconnects the SDK from the Kuzzle server using the underlying protocol `Disconnect` method. + +## Arguments + +```java +public void disconnect() +``` + +## Usage + +<<< ./snippets/disconnect.java diff --git a/doc/3/core-classes/kuzzle/disconnect/snippets/disconnect.java b/doc/3/core-classes/kuzzle/disconnect/snippets/disconnect.java new file mode 100644 index 00000000..e7a7f4d6 --- /dev/null +++ b/doc/3/core-classes/kuzzle/disconnect/snippets/disconnect.java @@ -0,0 +1 @@ +kuzzle.disconnect(); diff --git a/doc/3/core-classes/kuzzle/disconnect/snippets/disconnect.test.yml b/doc/3/core-classes/kuzzle/disconnect/snippets/disconnect.test.yml new file mode 100644 index 00000000..a9d9fe19 --- /dev/null +++ b/doc/3/core-classes/kuzzle/disconnect/snippets/disconnect.test.yml @@ -0,0 +1,8 @@ +--- +name: kuzzle#Disconnect +description: Disconnects the SDK to Kuzzle +hooks: + before: + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/core-classes/kuzzle/index.md b/doc/3/core-classes/kuzzle/index.md new file mode 100644 index 00000000..b6873810 --- /dev/null +++ b/doc/3/core-classes/kuzzle/index.md @@ -0,0 +1,7 @@ +--- +code: false +type: branch +order: 100 +title: Kuzzle +description: Kuzzle class +--- diff --git a/doc/3/core-classes/kuzzle/query/index.md b/doc/3/core-classes/kuzzle/query/index.md new file mode 100644 index 00000000..68f3884d --- /dev/null +++ b/doc/3/core-classes/kuzzle/query/index.md @@ -0,0 +1,51 @@ +--- +code: true +type: page +title: Query +description: Base method to send API query to Kuzzle +--- + +# query + +Base method used to send queries to Kuzzle, following the [API Documentation](/core/2/api). + +:::warning +This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods. +::: + +## Arguments + +```java +public CompletableFuture query( + final ConcurrentHashMap query) + throws InternalException, NotConnectedException +``` + +
+ +| Argument | Type | Description | +| --------- | ----------------- | ---------------------- | +| `query` |
ConcurrentHashMap
| API request | + +### query + +All properties necessary for the Kuzzle API can be added in the query object. +The following properties are the most common. + +| Property | Type | Description | +| ------------ | ----------------- | ---------------------------------------- | +| `controller` |
String
| Controller name (mandatory) | +| `action` |
String
| Action name (mandatory) | +| `body` |
ConcurrentHashMap
| Query body for this action | +| `index` |
String
| Index name for this action | +| `collection` |
String
| Collection name for this action | +| `_id` |
String
| id for this action | +| `volatile` |
ConcurrentHashMap
| Additional information to send to Kuzzle | + +## Returns + +Returns a [Response](/sdk/java/3/core-classes/response) object which represents a raw Kuzzle API response. See the [API Documentation](/core/2/api). + +## Usage + +<<< ./snippets/query.java diff --git a/doc/3/core-classes/kuzzle/query/snippets/query.java b/doc/3/core-classes/kuzzle/query/snippets/query.java new file mode 100644 index 00000000..76e76e85 --- /dev/null +++ b/doc/3/core-classes/kuzzle/query/snippets/query.java @@ -0,0 +1,13 @@ +ConcurrentHashMap query = new ConcurrentHashMap<>(); +query.put("controller", "document"); +query.put("action", "create"); +query.put("index", "nyc-open-data"); +query.put("collection", "yellow-taxi"); +query.put("_id", "my-custom-document-id"); +query.put("refresh", "wait_for"); +ConcurrentHashMap body = new ConcurrentHashMap<>(); +body.put("trip_distance", 4.23); +body.put("passenger_count", 2); +query.put("body", body); + +Response res = kuzzle.query(query).get(); diff --git a/doc/3/core-classes/kuzzle/query/snippets/query.test.yml b/doc/3/core-classes/kuzzle/query/snippets/query.test.yml new file mode 100644 index 00000000..87fbb5b7 --- /dev/null +++ b/doc/3/core-classes/kuzzle/query/snippets/query.test.yml @@ -0,0 +1,11 @@ +--- +name: kuzzle#Query +description: Sends a request to Kuzzle API +hooks: + before: | + curl -X POST kuzzle:7512/nyc-open-data/_create + curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi + curl -X DELETE kuzzle:7512/nyc-open-data/yellow-taxi/my-custom-document-id + after: +template: default +expected: Success \ No newline at end of file diff --git a/doc/3/core-classes/response/index.md b/doc/3/core-classes/response/index.md new file mode 100644 index 00000000..020ffc47 --- /dev/null +++ b/doc/3/core-classes/response/index.md @@ -0,0 +1,7 @@ +--- +code: true +type: branch +title: Response +description: Response object documentation +order: 0 +--- \ No newline at end of file diff --git a/doc/3/core-classes/response/introduction/index.md b/doc/3/core-classes/response/introduction/index.md new file mode 100644 index 00000000..a88bf823 --- /dev/null +++ b/doc/3/core-classes/response/introduction/index.md @@ -0,0 +1,30 @@ +--- +code: false +type: page +title: Introduction +description: Response object description +order: 0 +--- + +## Response + +`Response` is a **serializable** class representing a raw Kuzzle response. + +## Properties + +| Property | Type | Description | +|--- |--- |--- | +| `action` |
String
| Executed Kuzzle API controller's action | +| `collection` |
String
| Impacted collection | +| `controller` |
String
| Executed Kuzzle API controller | +| `error` |
[ErrorResponse](/sdk/java/3/core-classes/error-response)
| Error object (null if the request finished successfully) | +| `index` |
String
| Impacted index | +| `protocol` |
String
| Network protocol at the origin of the real-time notification | +| `requestId` |
String
| Request unique identifier | +| `result` |
Object
| Response payload (depends on the executed API action) | +| `room` |
String
| Room identifier (realtime only) | +| `scope` |
String
| Document scope ("in" or "out", realtime only) | +| `state` |
String
| Document state (realtime only) | +| `status` |
int
| Response status, following HTTP status codes | +| `timestamp` |
Long
| Notification timestamp (UTC) | +| `volatile` |
ConcurrentHashMap
| Volatile data | diff --git a/doc/3/core-classes/search-options/index.md b/doc/3/core-classes/search-options/index.md new file mode 100644 index 00000000..5f4967d6 --- /dev/null +++ b/doc/3/core-classes/search-options/index.md @@ -0,0 +1,31 @@ +--- +code: true +type: page +title: SearchOptions +description: SearchOptions class documentation +order: 110 +--- + +# SearchOptions + +This class represents the options usable with the search related methods. + +It can be used with the following methods: + - [document:search](/sdk/java/3/controllers/document/search) + - [collection:searchSpecifications](/sdk/java/3/controllers/collection/search-specifications) + +## Namespace + +You must include the following package: + +```java +import io.kuzzle.sdk.Options.SearchOptions; +``` + +## Properties + +| Property | Type | Description | +| -------- | --------------------- | ------------------------------------- | +| `from` |
Integer
| Offset of the first document to fetch | +| `scroll` |
String
| When set, gets a forward-only cursor having its ttl set to the given value (ie `1s`; cf [elasticsearch time limits](https://www.elastic.co/guide/en/elasticsearch/reference/7.3/common-options.html#time-units)) | +| `size` |
Integer
| Maximum number of documents to retrieve per page | diff --git a/doc/3/core-classes/search-result/index.md b/doc/3/core-classes/search-result/index.md new file mode 100644 index 00000000..924a90f8 --- /dev/null +++ b/doc/3/core-classes/search-result/index.md @@ -0,0 +1,6 @@ +--- +code: true +type: branch +title: SearchResult +description: SearchResult documentation +--- \ No newline at end of file diff --git a/doc/3/core-classes/search-result/introduction/index.md b/doc/3/core-classes/search-result/introduction/index.md new file mode 100644 index 00000000..e5f59ad9 --- /dev/null +++ b/doc/3/core-classes/search-result/introduction/index.md @@ -0,0 +1,42 @@ +--- +code: true +type: page +title: constructor +description: SearchResult:constructor +order: 1 +--- + +# SearchResults + +This class represents a paginated search result. + +It can be returned by the following methods: + - [document:search](/sdk/java/3/controllers/document/search) + - [collection:searchSpecifications](/sdk/java/3/controllers/collection/search-specifications) + +## Namespace + +You must include the following package: + +```java +import io.kuzzle.sdk.CoreClasses.SearchResult; +``` + +## Properties + +| Property | Type | Description | +| -------------- | ------------------------------------------------------- | ------------------ | +| `aggregations` |
ConcurrentHashMap
| Search aggregations (can be undefined) | +| `hits` |
ArrayList>
| Page results | +| `total` |
Integer
| Total number of items that _can_ be retrieved | +| `fetched` |
Integer
| Number of retrieved items so far | + +### hits + +Each element of the `hits` ArrayList is a `ConcurrentHashMap` containing the following properties: + +| Property | Type | Description | +| --------- | ------------------ | ---------------------- | +| `_id` |
String
| Document ID | +| `_score` |
Integer
| [Relevance score](https://www.elastic.co/guide/en/elasticsearch/guide/current/relevance-intro.html) | +| `_source` |
ConcurrentHashMap
| Document content | \ No newline at end of file diff --git a/doc/3/core-classes/search-result/next/index.md b/doc/3/core-classes/search-result/next/index.md new file mode 100644 index 00000000..0b25a195 --- /dev/null +++ b/doc/3/core-classes/search-result/next/index.md @@ -0,0 +1,74 @@ +--- +code: true +type: page +title: next +description: SearchResult next method +order: 200 +--- + +# next + +Advances through the search results and returns the next page of items. + +## Arguments + +```java +public CompletableFuture next() +``` + +## Returns + +Returns a `SearchResult` object, or `null` if no more pages are available. + +## Throw + +This method throws an exception if: + +- No pagination strategy can be applied (see below) +- If invoking it would lead to more than 10 000 items being retrieved with the `from/size` strategy + +## Pagination strategies + +Depending on the arguments given to the initial search, the `next` method will pick one of the following strategies, by decreasing order of priority. + +### Strategy: scroll cursor + +If the original search query is given a `scroll` parameter, the `next` method uses a cursor to paginate results. + +The results from a scroll request are frozen, and reflect the state of the index at the time the initial `search` request. +For that reason, this method is guaranteed to return consistent results, even if documents are updated or deleted in the database between two pages retrieval. + +This is the most consistent way to paginate results, however, this comes at a higher computing cost for the server. + +::: warning +When using a cursor with the `scroll` option, Elasticsearch has to duplicate the transaction log to keep the same result during the entire scroll session. +It can lead to memory leaks if ascroll duration too great is provided, or if too many scroll sessions are open simultaneously. +::: + +::: info + +You can restrict the scroll session maximum duration under the `services.storage.maxScrollDuration` configuration key. +::: + +<<< ./snippets/scroll.java + +### Strategy: sort / size + +If the initial search contains `sort` and `size` parameters, the `next` method retrieves the next page of results following the sort order, the last item of the current page acting as a live cursor. + +To avoid too many duplicates, it is advised to provide a sort combination that will always identify one item only. The recommended way is to use the field `_uid` which is certain to contain one unique value for each document. + +Because this method does not freeze the search results between two calls, there can be missing or duplicated documents between two result pages. + +This method efficiently mitigates the costs of scroll searches, but returns less consistent results: it's a middle ground, ideal for real-time search requests. + +### Strategy: from / size + +If the initial search contains `from` and `size` parameters, the `next` method retrieves the next page of result by incrementing the `from` offset. + +Because this method does not freeze the search results between two calls, there can be missing or duplicated documents between two result pages. + +It's the fastest pagination method available, but also the less consistent, and it is not possible to retrieve more than 10000 items using it. +Above that limit, any call to `next` throws an Exception. + +<<< ./snippets/fromsize.java diff --git a/doc/3/core-classes/search-result/next/snippets/fromsize.java b/doc/3/core-classes/search-result/next/snippets/fromsize.java new file mode 100644 index 00000000..3a6e0540 --- /dev/null +++ b/doc/3/core-classes/search-result/next/snippets/fromsize.java @@ -0,0 +1,51 @@ + ArrayList> documents = new ArrayList<>(); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + + body.put("category", "suv"); + for (int i = 0; i < 100; i++) { + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("_id", "suv_no" + i); + document.put("body", body); + documents.add(document); + } + + kuzzle + .getDocumentController() + .mCreate("nyc-open-data", "yellow-taxi", documents, true).get(); + + SearchOptions options = new SearchOptions(); + options.setFrom(1); + options.setSize(5); + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("category", "suv"); + query.put("match", match); + searchQuery.put("query", query); + + SearchResult results = kuzzle.getDocumentController().search( + "nyc-open-data", + "yellow-taxi", + searchQuery, options).get(); + + // Fetch the matched items by advancing through the result pages + ArrayList> matched = new ArrayList<>(); + + while (results != null) { + matched.addAll(results.hits); + results = results.next().get(); + } + + /* + { _id="suv_no1", + _score=0.03390155, + _source= + { _kuzzle_info= + { author="-1", + updater=null, + updatedAt=null, + createdAt=1570093133057 }, + category="suv" } } + */ + System.out.println("Successfully retrieved " + matched.size() + " documents"); \ No newline at end of file diff --git a/doc/3/core-classes/search-result/next/snippets/fromsize.test.yml b/doc/3/core-classes/search-result/next/snippets/fromsize.test.yml new file mode 100644 index 00000000..f05d17ee --- /dev/null +++ b/doc/3/core-classes/search-result/next/snippets/fromsize.test.yml @@ -0,0 +1,11 @@ +name: searchresult#fromsize +description: Next method with from/size +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: | + curl -XDELETE kuzzle:7512/nyc-open-data +template: default +expected: Successfully retrieved 100 documents \ No newline at end of file diff --git a/doc/3/core-classes/search-result/next/snippets/scroll.java b/doc/3/core-classes/search-result/next/snippets/scroll.java new file mode 100644 index 00000000..51ee6c38 --- /dev/null +++ b/doc/3/core-classes/search-result/next/snippets/scroll.java @@ -0,0 +1,52 @@ + ArrayList> documents = new ArrayList<>(); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + + body.put("category", "suv"); + + for (int i = 0; i < 100; i++) { + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("_id", "suv_no" + i); + document.put("body", body); + documents.add(document); + } + + kuzzle + .getDocumentController() + .mCreate("nyc-open-data", "yellow-taxi", documents, true).get(); + + SearchOptions options = new SearchOptions(); + options.setScroll("1s"); + options.setSize(10); + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("category", "suv"); + query.put("match", match); + searchQuery.put("query", query); + + SearchResult results = kuzzle.getDocumentController().search( + "nyc-open-data", + "yellow-taxi", + searchQuery, options).get(); + + // Fetch the matched items by advancing through the result pages + ArrayList> matched = new ArrayList<>(); + + while (results != null) { + matched.addAll(results.hits); + results = results.next().get(); + } + + /* + { _id="suv_no1", + _score=0.03390155, + _source= + { _kuzzle_info= + { author="-1", + updater=null, + updatedAt=null, + createdAt=1570093133057 }, + category="suv" } } + */ + System.out.println("Successfully retrieved " + matched.size() + " documents"); diff --git a/doc/3/core-classes/search-result/next/snippets/scroll.test.yml b/doc/3/core-classes/search-result/next/snippets/scroll.test.yml new file mode 100644 index 00000000..69926783 --- /dev/null +++ b/doc/3/core-classes/search-result/next/snippets/scroll.test.yml @@ -0,0 +1,11 @@ +name: searchresult#scroll +description: Next method with scroll +hooks: + before: | + curl -XDELETE kuzzle:7512/nyc-open-data + curl -XPOST kuzzle:7512/nyc-open-data/_create + curl -XPUT kuzzle:7512/nyc-open-data/yellow-taxi + after: | + curl -XDELETE kuzzle:7512/nyc-open-data +template: default +expected: Successfully retrieved 100 documents \ No newline at end of file diff --git a/doc/3/core-classes/subscribe-options/index.md b/doc/3/core-classes/subscribe-options/index.md new file mode 100644 index 00000000..f166e69d --- /dev/null +++ b/doc/3/core-classes/subscribe-options/index.md @@ -0,0 +1,28 @@ +--- +code: true +type: page +title: SubscribeOptions +description: SubscribeOptions class documentation +order: 110 +--- + +# SubscribeOptions + +This class represents the options usable with the [RealtimeController.subscribe](/sdk/java/3/controllers/realtime/subscribe) method. + +## Namespace + +You must include the following package: + +```java +import io.kuzzle.sdk.Options.SubscribeOptions; +``` + +## Properties + +| Property | Type
(default) | Description | writable | +|----------|--------------------|------------------| ------- | +| `Scope` |
Scope

(`ALL`) | Subscribes to document entering or leaving the scope
Possible values: `ALL`, `IN`, `OUT`, `NONE`| yes | +| `Users` |
Users

(`NONE`) | Subscribes to users entering or leaving the room
Possible values: `ALL`, `IN`, `OUT`, `NONE`| yes | +| `SubscribeToSelf` |
boolean

(`true`) | Subscribes to notifications fired by our own queries | yes | +| `Volatile` |
ConcurrentHashMap

(`null`) | ConcurrentHashMap representing subscription information, used in [user join/leave notifications](/core/2/api/essentials/volatile-data) |yes | diff --git a/doc/3/core-classes/update-options/index.md b/doc/3/core-classes/update-options/index.md new file mode 100644 index 00000000..a13db359 --- /dev/null +++ b/doc/3/core-classes/update-options/index.md @@ -0,0 +1,27 @@ +--- +code: true +type: page +title: UpdateOptions +description: UpdateOptions class documentation +order: 110 +--- + +# UpdateOptions + +This class represents the options usable with the [`update`](/sdk/java/3/controllers/document/update) method of the [DocumentController](/sdk/java/3/controllers/document). + +## Namespace + +You must include the following package: + +```java +import io.kuzzle.sdk.Options.UpdateOptions; +``` + +## Properties + +| Property | Type | Description | +| ------------------ | -------------------------------------------- | --------------------------------- | +| `waitForRefresh` |
Boolean
(optional) | If set to `true`, Kuzzle will wait for the persistence layer to finish indexing | +| `retryOnConflict` |
Integer
| The number of times the database layer should retry in case of version conflict | +| `source` |
Boolean
| If true, returns the updated document inside the response | diff --git a/doc/3/essentials/index.md b/doc/3/essentials/index.md new file mode 100644 index 00000000..5ed4b8a5 --- /dev/null +++ b/doc/3/essentials/index.md @@ -0,0 +1,7 @@ +--- +code: false +type: branch +order: 20 +title: Essentials +description: Kuzzle Java SDK essentials guides +--- diff --git a/doc/3/essentials/network-loss-resilience/index.md b/doc/3/essentials/network-loss-resilience/index.md new file mode 100644 index 00000000..ecda8d05 --- /dev/null +++ b/doc/3/essentials/network-loss-resilience/index.md @@ -0,0 +1,19 @@ +--- +code: false +type: page +title: Network Loss Resilience +description: Learn how to use the Kuzzle JAVA SDK with an instable network +order: 400 +--- + +# Network Loss Resilience + +The Kuzzle JAVA SDK provides tools that allow it to be used with an unstable network connection. + +## Automatic reconnection & resubscription + +The Kuzzle JAVA SDK can automatically reconnect in case of a network disconnection and it can renew realtime subscriptions if there are any. + +To control the auto reconnection feature with WebSocket (enabled by default), refer to the `autoReconnect` option of the [WebSocketOptions](/sdk/java/3/protocols/websocket-options) object. + +To control the auto resubscription (enabled by default), refer to the `autoResubscribe` option of the [KuzzleOptions](/sdk/java/3/core-classes/kuzzle-options) object. diff --git a/doc/3/essentials/realtime-notifications/index.md b/doc/3/essentials/realtime-notifications/index.md new file mode 100644 index 00000000..cddb2c16 --- /dev/null +++ b/doc/3/essentials/realtime-notifications/index.md @@ -0,0 +1,32 @@ +--- +code: false +type: page +title: Realtime notifications +description: List of realtime notifications sent by Kuzzle +order: 300 +--- + +# Notifications + +The [RealtimeController.subscribe](/sdk/java/3/controllers/realtime/subscribe) method takes a handler argument, called with a [Response](/sdk/java/3/core-classes/response) object, whose content of the `Result` property depends on the type of notification received. + +## Document & messages + +These notifications represent [documents changes & messages](/core/2/api/essentials/notifications#documents-changes-messages). + +The `Result` ConcurrentHashMap is the notification content, and it has the following structure: + +| Property | Type | Description | +| --------- | ----------------- | --------------------------------------------------------------------------------------- | +| `_id` |
String
| Document unique ID
`null` if the notification is from a real-time message | +| `_source` |
ConcurrentHashMap
| Message or full document content. Not present if the event is about a document deletion | + +## User + +These notifications represent [user events](/core/2/api/essentials/notifications#user-notification). + +The `Result` JObject is the notification content, and it has the following structure: + +| Property | Type | Description | +| -------- | ----------------- | -------------------------------------------------- | +| `count` |
Long
| Updated users count sharing that same subscription | diff --git a/doc/3/exceptions/illegal-argument-exception/index.md b/doc/3/exceptions/illegal-argument-exception/index.md new file mode 100644 index 00000000..23fe27a7 --- /dev/null +++ b/doc/3/exceptions/illegal-argument-exception/index.md @@ -0,0 +1,11 @@ +--- +code: true +type: page +title: IllegalArgumentException +description: IllegalArgumentException +order: 10 +--- + +# IllegalArgumentException + +The `IllegalArgumentException` class is thrown when a bad argument is passed. diff --git a/doc/3/exceptions/index.md b/doc/3/exceptions/index.md new file mode 100644 index 00000000..0cadf3c0 --- /dev/null +++ b/doc/3/exceptions/index.md @@ -0,0 +1,7 @@ +--- +code: false +type: branch +order: 80 +title: Exceptions +description: Kuzzle Java SDK exceptions +--- diff --git a/doc/3/getting-started/index.md b/doc/3/getting-started/index.md new file mode 100644 index 00000000..150d6807 --- /dev/null +++ b/doc/3/getting-started/index.md @@ -0,0 +1,6 @@ +--- +code: false +type: branch +order: 0 +title: Getting Started +--- diff --git a/doc/3/getting-started/install/index.md b/doc/3/getting-started/install/index.md new file mode 100644 index 00000000..3f8e164b --- /dev/null +++ b/doc/3/getting-started/install/index.md @@ -0,0 +1,120 @@ +--- +code: false +type: page +title: Getting started +description: Java Getting started +order: 99 +--- + +# Getting Started + +In this tutorial you will learn how to install the Kuzzle **Java SDK**. +This page shows examples of scripts that **store** documents in Kuzzle, and of scripts that subcribe to real-time **notifications** for each new document created. + +::: success +Before proceeding, please make sure your system meets the following requirements: + +- **Oracle JDK or OpenJDK** version 8 or higher ([OpenJDK installation instructions](https://openjdk.java.net/install/)) +- A running Kuzzle Server ([Kuzzle installation guide](/core/2/guides/essentials/installing-kuzzle)) + +::: + + +::: info +Having trouble? Get in touch with us on [Discord](http://join.discord.kuzzle.io)! +::: + +## Installation + +You can find the SDK JARs directly on [bintray](https://bintray.com/kuzzle/maven/kuzzle-sdk-java). Download and add it to your classpath. + +::: info +The following examples are made to be executed without any IDE. +If you're using Eclipse, IntelliJ or another Java IDE, you need to add the SDK as a project dependency in your classpath. +::: + +## First connection + +Initialize a new Java project, create a `gettingstartedfirstconnection.java` file and start by adding the code below: + +<<< ./snippets/firstconnection.java + +This program initializes the Kuzzle Server storage by creating a index, and a collection inside it +Run the program with the following command: + +```bash +$ javac -classpath ./path/to/the/sdk.jar gettingstartedfirstconnection.java +$ java -classpath .:./path/to/the/sdk.jar gettingstartedfirstconnection +Connected! +Index nyc-open-data created! +Collection yellow-taxi created! +``` + +Congratulations, you performed your first connection to Kuzzle Server via a Java program. +You now know how to: + +- Instantiate Kuzzle SDK and connect to Kuzzle Server using a specific protocol (here `websocket`) +- Create a index +- Create a collection within an existing index + +## Create your first document + +Now that you successfully connected to your Kuzzle Server instance, and created an index and a collection, it's time to manipulate some data. + +Here is how Kuzzle structures its storage space: + +- indexes contain collections +- collections contain documents + Create a `gettingstartedstorage.java` file in the playground and add this code: + +<<< ./snippets/document.java + +As you did before, build and run your program: + +```bash +$ javac -classpath ./path/to/the/sdk.jar gettingstartedstorage.java +$ java -classpath .:./path/to/the/sdk.jar gettingstartedstorage +Connected! +New document added to yellow-taxi collection! +``` + +You can perform other actions such as [delete](/sdk/java/3/controllers/document/delete), [replace](/sdk/java/3/controllers/document/replace) or [search](/sdk/java/3/controllers/document/search) documents. There are also other ways to interact with Kuzzle like our [Admin Console](/core/2/guides/essentials/admin-console), the [Kuzzle HTTP API](/core/2/api/essentials/connecting-to-kuzzle) or by using your [own protocol](/core/2/protocols/essentials/getting-started). + +Now you know how to: + +- Store documents in a Kuzzle Server, and access those + +## Subscribe to realtime document notifications (pub/sub) + +Time to use realtime with Kuzzle. Create a new file `gettingstartedrealtime.java` with the following code: + +<<< ./snippets/realtime.java + +This program subscribes to changes made to documents with a `license` field set to `B`, within the `yellow-taxi` collection. Whenever a document matching the provided filters changes, a new notification is received from Kuzzle. + +Build and run your program: + +```bash +$ javac -classpath ./path/to/the/sdk.jar gettingstartedrealtime.java +$ java -classpath .:./path/to/the/sdk.jar gettingstartedrealtime +Connected! +Successfully subscribing! +New document added to yellow-taxi collection! +New created document notification: [Document content as ConcurrentHashMap] +``` + +You should see document content as a `ConcurrentHashMap`. + +Now, you know how to: + +- Create realtime filters +- Subscribe to notifications + +## Where do we go from here? + +Now that you're more familiar with the Java SDK, you can dive even deeper to learn how to leverage its full capabilities: + +- discover what this SDK has to offer by browsing other sections of this documentation +- learn how to use [Koncorde](/core/2/guides/cookbooks/realtime-api) to create incredibly fine-grained and blazing-fast subscriptions +- follow our guide to learn how to perform [basic authentication](/core/2/guides/essentials/user-authentication#local-strategy) +- follow our guide to learn how to [manage users and how to set up fine-grained access control](/core/2/guides/essentials/security) \ No newline at end of file diff --git a/doc/3/getting-started/install/snippets/document.java b/doc/3/getting-started/install/snippets/document.java new file mode 100644 index 00000000..47008b1b --- /dev/null +++ b/doc/3/getting-started/install/snippets/document.java @@ -0,0 +1,50 @@ +import io.kuzzle.sdk.*; +import io.kuzzle.sdk.Options.KuzzleOptions; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Protocol.WebSocket; + +import java.util.concurrent.ConcurrentHashMap; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] args) { + + try { + // Creates a WebSocket connection. + // Replace "kuzzle" with + // your Kuzzle hostname like "localhost" + WebSocketOptions opts = new WebSocketOptions(); + opts.setAutoReconnect(true).setConnectionTimeout(42000); + + WebSocket ws = new WebSocket("kuzzle", opts); + + // Instantiates a Kuzzle client + kuzzle = new Kuzzle(ws, (KuzzleOptions) null); + + // Connects to the server. + kuzzle.connect(); + System.out.println("Connected!"); + } catch(Exception e){ + e.printStackTrace(); + } + + // New document content + ConcurrentHashMap content = new ConcurrentHashMap<>(); + content.put("name", "John"); + content.put("birthday", "1995-11-27"); + content.put("license", "B"); + + // Stores the document in the "yellow-taxi" collection. + try { + kuzzle.getDocumentController() + .create( "nyc-open-data", "yellow-taxi", content).get(); + System.out.println("New document added to the yellow-taxi collection!"); + } catch(Exception e){ + e.printStackTrace(); + } + + // Disconnects the SDK. + kuzzle.disconnect(); + } +} \ No newline at end of file diff --git a/doc/3/getting-started/install/snippets/document.test.yml b/doc/3/getting-started/install/snippets/document.test.yml new file mode 100644 index 00000000..d1a79d2f --- /dev/null +++ b/doc/3/getting-started/install/snippets/document.test.yml @@ -0,0 +1,9 @@ +name: gettingstarted#storage +description: Data manipulation +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create ; curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi/; curl -X DELETE kuzzle:7512/nyc-open-data/yellow-taxi/some-id + after: +template: empty +expected: + - Connected! + - New document added to the yellow-taxi collection! \ No newline at end of file diff --git a/doc/3/getting-started/install/snippets/firstconnection.java b/doc/3/getting-started/install/snippets/firstconnection.java new file mode 100644 index 00000000..6676e9ed --- /dev/null +++ b/doc/3/getting-started/install/snippets/firstconnection.java @@ -0,0 +1,52 @@ +import io.kuzzle.sdk.*; +import io.kuzzle.sdk.Options.KuzzleOptions; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Protocol.WebSocket; + +import java.util.concurrent.ConcurrentHashMap; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] args) { + + try { + // Creates a WebSocket connection. + // Replace "kuzzle" with + // your Kuzzle hostname like "localhost" + WebSocketOptions opts = new WebSocketOptions(); + opts.setAutoReconnect(true).setConnectionTimeout(42000); + + WebSocket ws = new WebSocket("kuzzle", opts); + + // Instantiates a Kuzzle client + kuzzle = new Kuzzle(ws, (KuzzleOptions) null); + + // Connects to the server. + kuzzle.connect(); + System.out.println("Connected!"); + } catch(Exception e){ + e.printStackTrace(); + } + + // Freshly installed Kuzzle servers are empty: we need to create + // a new index. + try { + kuzzle.getIndexController().create("nyc-open-data").get(); + System.out.println("Index nyc-open-data created!"); + } catch(Exception e){ + e.printStackTrace(); + } + + // Creates a collection + try { + kuzzle.getCollectionController().create("nyc-open-data", "yellow-taxi").get(); + System.out.println("Collection yellow-taxi created!"); + } catch(Exception e){ + e.printStackTrace(); + } + + // Disconnects the SDK + kuzzle.disconnect(); + } +} \ No newline at end of file diff --git a/doc/3/getting-started/install/snippets/firstconnection.test.yml b/doc/3/getting-started/install/snippets/firstconnection.test.yml new file mode 100644 index 00000000..f7201621 --- /dev/null +++ b/doc/3/getting-started/install/snippets/firstconnection.test.yml @@ -0,0 +1,10 @@ +name: gettingstarted#firstconnection +description: First connection +hooks: + before: curl -X DELETE kuzzle:7512/nyc-open-data + after: +template: empty +expected: + - Connected! + - Index nyc-open-data created! + - Collection yellow-taxi created! diff --git a/doc/3/getting-started/install/snippets/realtime.java b/doc/3/getting-started/install/snippets/realtime.java new file mode 100644 index 00000000..59600632 --- /dev/null +++ b/doc/3/getting-started/install/snippets/realtime.java @@ -0,0 +1,68 @@ +import io.kuzzle.sdk.*; +import io.kuzzle.sdk.Options.KuzzleOptions; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Protocol.WebSocket; + +import java.util.concurrent.ConcurrentHashMap; + +public class SnippetTest { + private static Kuzzle kuzzle; + + public static void main(String[] args) { + + try { + // Creates a WebSocket connection. + // Replace "kuzzle" with + // your Kuzzle hostname like "localhost" + WebSocketOptions opts = new WebSocketOptions(); + opts.setAutoReconnect(true).setConnectionTimeout(42000); + + WebSocket ws = new WebSocket("kuzzle", opts); + + // Instantiates a Kuzzle client + kuzzle = new Kuzzle(ws, (KuzzleOptions) null); + + // Connects to the server. + kuzzle.connect(); + System.out.println("Connected!"); + } catch (Exception e) { + e.printStackTrace(); + } + + // Subscribes to notifications for drivers having a "B" driver license. + ConcurrentHashMap filters = new ConcurrentHashMap<>(); + ConcurrentHashMap equals = new ConcurrentHashMap<>(); + equals.put("license", "B"); + filters.put("equals", equals); + + try { + // Sends the subscription + kuzzle.getRealtimeController() + .subscribe("nyc-open-data", "yellow-taxi", filters, notification -> { + ConcurrentHashMap content = ((ConcurrentHashMap)(notification.result)); + System.out.println("New created document notification: " + content); + }).get(); + System.out.println("Successfully subscribed!"); + } catch (Exception e) { + e.printStackTrace(); + } + + // Writes a new document. This triggers a notification + // sent to our subscription. + ConcurrentHashMap content = new ConcurrentHashMap<>(); + content.put("name", "John"); + content.put("birthday", "1995-11-27"); + content.put("license", "B"); + + try { + kuzzle.getDocumentController() + .create("nyc-open-data", "yellow-taxi", content).get(); + System.out.println("New document added to the yellow-taxi collection!"); + } catch (Exception e) { + e.printStackTrace(); + } + + // Disconnects the SDK. + kuzzle.disconnect(); + } +} \ No newline at end of file diff --git a/doc/3/getting-started/install/snippets/realtime.test.yml b/doc/3/getting-started/install/snippets/realtime.test.yml new file mode 100644 index 00000000..0f45f938 --- /dev/null +++ b/doc/3/getting-started/install/snippets/realtime.test.yml @@ -0,0 +1,10 @@ +name: gettingstarted#realtime +description: Realtime interactions +hooks: + before: curl -X POST kuzzle:7512/nyc-open-data/_create ; curl -X PUT kuzzle:7512/nyc-open-data/yellow-taxi/ + after: +template: empty +expected: + - Connected! + - Successfully subscribed! + - ^New created document notification:.*$ diff --git a/doc/3/index.md b/doc/3/index.md new file mode 100644 index 00000000..6642becc --- /dev/null +++ b/doc/3/index.md @@ -0,0 +1,7 @@ +--- +code: false +type: root +order: 9 +title: JAVA SDK +description: JAVA SDK 3.x +--- diff --git a/doc/3/protocols/index.md b/doc/3/protocols/index.md new file mode 100644 index 00000000..b2ad68fb --- /dev/null +++ b/doc/3/protocols/index.md @@ -0,0 +1,7 @@ +--- +code: false +type: branch +order: 60 +title: Protocols +description: Kuzzle Java SDK available protocol classes +--- diff --git a/doc/3/protocols/websocket-options/index.md b/doc/3/protocols/websocket-options/index.md new file mode 100644 index 00000000..0c0cd749 --- /dev/null +++ b/doc/3/protocols/websocket-options/index.md @@ -0,0 +1,74 @@ +--- +code: true +type: page +title: WebSocketOptions +description: KuzzleOptions class documentation +order: 110 +--- + +# WebSocketOptions + +This class represents the options usable with the Kuzzle class. + +It can be used with the following methods: + - [WebSocket.WebSocket](/sdk/java/3/protocols/websocket) + +# Constructor + +This class has a constructor and a constructor by copy. + +## Getters and setters + +### port + +The port to use to connect. + +```java +public int getPort(); +public WebSocketOptions setPort(int port) +``` + +### ssl + +If we use SSL connection. + +```java +public boolean getSsl() +public WebSocketOptions setSsl(boolean ssl) +``` + +### connectionTimeout + +The duration before the connection timeout. + +```java +public int getConnectionTimeout() +public WebSocketOptions setConnectionTimeout(int connectionTimeout) +``` + +### autoReconnect + +If the websocket auto reconnects. + +```java +public boolean getAutoReconnect() +public WebSocketOptions setAutoReconnect(boolean autoReconnect) +``` + +### reconnectionDelay + +Time between each reconnection attempt. + +```java +public long getReconnectionDelay(); +public WebSocketOptions setReconnectionDelay(long reconnectionDelay); +``` + +### reconnectionRetries + +Number of attempts to try and reconnect. -1 for infinite attempts until the connection is established again. + +```java +public long getReconnectionRetries(); +public WebSocketOptions setReconnectionRetries(long reconnectionRetries); +``` diff --git a/doc/3/protocols/websocket/constructor/index.md b/doc/3/protocols/websocket/constructor/index.md new file mode 100644 index 00000000..d136c3f7 --- /dev/null +++ b/doc/3/protocols/websocket/constructor/index.md @@ -0,0 +1,72 @@ +--- +code: true +type: page +title: Constructor +description: Creates a new WebSocket protocol +order: 50 +--- + +# Constructor + +Initializes a new instance of the WebSocket class pointing to the Kuzzle server specified by the uri. + +## Arguments + +```java +public WebSocket(URI uri, WebSocketOptions options) throws URISyntaxException, IllegalArgumentException +``` + +
+ +| Argument | Type | Description | +| --------- | ----------------- | ---------------------------- | +| `uri` |
Uri
| URI pointing to a Kuzzle server | +| `options` |
WebSocketOptions
| Class which contains websocket options | + +### uri + +A Uri object pointing to a Kuzzle server. + +Use `wss://:` to initiate a secure SSL connection. + +## options + +The options used to connect to the Kuzzle instance. +[WebSocketOptions](/sdk/java/3/protocols/websocket-options) + +## Return + +A `WebSocket` protocol instance. + +## Arguments + +```java +public WebSocket(String host, WebSocketOptions options) + throws URISyntaxException, IllegalArgumentException +``` + +
+ +| Argument | Type | Description | +| --------- | ----------------- | ---------------------------- | +| `host` |
String
| Host pointing to a Kuzzle server | +| `options` |
WebSocketOptions
| Class which contains websocket options | + +### host + +A host pointing to a Kuzzle server. + +Use `wss://:` to initiate a secure SSL connection. + +## options + +The options used to connect to the Kuzzle instance. +[WebSocketOptions](/sdk/java/3/protocols/websocket-options) + +## Return + +A `WebSocket` protocol instance. + +## Usage + +<<< ./snippets/constructor.java diff --git a/doc/3/protocols/websocket/constructor/snippets/constructor.java b/doc/3/protocols/websocket/constructor/snippets/constructor.java new file mode 100644 index 00000000..d7fccde8 --- /dev/null +++ b/doc/3/protocols/websocket/constructor/snippets/constructor.java @@ -0,0 +1,7 @@ +WebSocketOptions options = new WebSocketOptions(); +options.setAutoReconnect(true) + .setConnectionTimeout(42000) + .setPort(7513) + .setSsl(false); + +WebSocket ws = new WebSocket("localhost", options); diff --git a/doc/3/protocols/websocket/constructor/snippets/constructor.test.yml b/doc/3/protocols/websocket/constructor/snippets/constructor.test.yml new file mode 100644 index 00000000..419028a7 --- /dev/null +++ b/doc/3/protocols/websocket/constructor/snippets/constructor.test.yml @@ -0,0 +1,8 @@ +--- +name: websocket#constructor +description: Creates a new WebSocket instance +hooks: + before: + after: +template: without-ctor +expected: Success \ No newline at end of file diff --git a/doc/3/protocols/websocket/index.md b/doc/3/protocols/websocket/index.md new file mode 100644 index 00000000..8185611a --- /dev/null +++ b/doc/3/protocols/websocket/index.md @@ -0,0 +1,7 @@ +--- +code: true +type: branch +title: WebSocket +description: WebSocket protocol documentation +order: 0 +--- \ No newline at end of file diff --git a/doc/doc.sh b/doc/doc.sh old mode 100644 new mode 100755 index e0e4a476..b7d98fa9 --- a/doc/doc.sh +++ b/doc/doc.sh @@ -2,51 +2,55 @@ set -eu -DOC_VERSION=2 -DOC_PATH=/sdk/java/2 +DOC_VERSION=3 +DOC_PATH=/sdk/java/3 +PWD=$(dirname $(readlink -f $0)) +FMWKDIR="$PWD/framework" +FMWKTARGET="$FMWKDIR/src$DOC_PATH" +VUEPRESS="$FMWKDIR/node_modules/.bin/vuepress" # Used by vuepress -export DOC_DIR=$DOC_VERSION +export DOC_DIR="$PWD/${DOC_VERSION}" export SITE_BASE=$DOC_PATH/ # Used to specify --no-cache for example ARGS=${2:-""} -if [ ! -d "./$DOC_DIR" ] +if [ ! -d "$DOC_DIR" ] then - echo "Cannot find $DOC_DIR/. You must run this script from doc/ directory." + echo "Cannot find documentation directory: $DOC_DIR" exit 1 fi case $1 in prepare) echo "Clone documentation framework" - rm -rf framework/ - git clone --depth 10 --single-branch --branch master https://github.com/kuzzleio/documentation.git framework/ + rm -rf $FMWKDIR + git clone --depth 10 --single-branch --branch master https://github.com/kuzzleio/documentation.git $FMWKDIR echo "Link local doc for dead links checking" - rm framework/src$DOC_PATH - ln -s ../../../../$DOC_VERSION framework/src$DOC_PATH + rm $FMWKTARGET + ln -s ${DOC_DIR} $FMWKTARGET echo "Install dependencies" - npm --prefix framework/ install + npm --prefix $FMWKDIR ci ;; dev) - ./framework/node_modules/.bin/vuepress dev $DOC_VERSION/ $ARGS + $VUEPRESS dev $DOC_DIR/ $ARGS ;; build) - ./framework/node_modules/.bin/vuepress build $DOC_VERSION/ $ARGS + $VUEPRESS build $DOC_DIR/ $ARGS ;; build-netlify) export SITE_BASE="/" - ./framework/node_modules/.bin/vuepress build $DOC_VERSION/ $ARGS + $VUEPRESS build $DOC_DIR/ $ARGS ;; upload) - aws s3 sync $DOC_VERSION/.vuepress/dist s3://$S3_BUCKET$SITE_BASE + aws s3 sync $DOC_DIR/.vuepress/dist s3://$S3_BUCKET$SITE_BASE ;; cloudfront) diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index c44b679a..f3d88b1c 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 8daee4f4..ba94df84 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Wed Jun 19 10:16:14 CEST 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-all.zip diff --git a/gradlew b/gradlew index cccdd3d5..2fe81a7d 100755 --- a/gradlew +++ b/gradlew @@ -1,5 +1,21 @@ #!/usr/bin/env sh +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + ############################################################################## ## ## Gradle start up script for UN*X @@ -28,7 +44,7 @@ APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" @@ -109,8 +125,8 @@ if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` @@ -138,19 +154,19 @@ if $cygwin ; then else eval `echo args$i`="\"$arg\"" fi - i=$((i+1)) + i=`expr $i + 1` done case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi @@ -159,14 +175,9 @@ save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } -APP_ARGS=$(save "$@") +APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index e95643d6..24467a14 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -14,7 +30,7 @@ set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..de91bef3 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1525 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@babel/runtime": { + "version": "7.7.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.7.7.tgz", + "integrity": "sha512-uCnC2JEVAu8AKB5do1WRIsvrdJ0flYx/A/9f/6chdacnEZ7LmavjdsDXr5ksYBegxtuTPR5Va9/+13QF/kFkCA==", + "requires": { + "regenerator-runtime": "^0.13.2" + } + }, + "@oclif/command": { + "version": "1.5.19", + "resolved": "https://registry.npmjs.org/@oclif/command/-/command-1.5.19.tgz", + "integrity": "sha512-6+iaCMh/JXJaB2QWikqvGE9//wLEVYYwZd5sud8aLoLKog1Q75naZh2vlGVtg5Mq/NqpqGQvdIjJb3Bm+64AUQ==", + "requires": { + "@oclif/config": "^1", + "@oclif/errors": "^1.2.2", + "@oclif/parser": "^3.8.3", + "@oclif/plugin-help": "^2", + "debug": "^4.1.1", + "semver": "^5.6.0" + } + }, + "@oclif/config": { + "version": "1.13.3", + "resolved": "https://registry.npmjs.org/@oclif/config/-/config-1.13.3.tgz", + "integrity": "sha512-qs5XvGRw+1M41abOKCjd0uoeHCgsMxa2MurD2g2K8CtQlzlMXl0rW5idVeimIg5208LLuxkfzQo8TKAhhRCWLg==", + "requires": { + "@oclif/parser": "^3.8.0", + "debug": "^4.1.1", + "tslib": "^1.9.3" + } + }, + "@oclif/errors": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@oclif/errors/-/errors-1.2.2.tgz", + "integrity": "sha512-Eq8BFuJUQcbAPVofDxwdE0bL14inIiwt5EaKRVY9ZDIG11jwdXZqiQEECJx0VfnLyUZdYfRd/znDI/MytdJoKg==", + "requires": { + "clean-stack": "^1.3.0", + "fs-extra": "^7.0.0", + "indent-string": "^3.2.0", + "strip-ansi": "^5.0.0", + "wrap-ansi": "^4.0.0" + } + }, + "@oclif/linewrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@oclif/linewrap/-/linewrap-1.0.0.tgz", + "integrity": "sha512-Ups2dShK52xXa8w6iBWLgcjPJWjais6KPJQq3gQ/88AY6BXoTX+MIGFPrWQO1KLMiQfoTpcLnUwloN4brrVUHw==" + }, + "@oclif/parser": { + "version": "3.8.4", + "resolved": "https://registry.npmjs.org/@oclif/parser/-/parser-3.8.4.tgz", + "integrity": "sha512-cyP1at3l42kQHZtqDS3KfTeyMvxITGwXwH1qk9ktBYvqgMp5h4vHT+cOD74ld3RqJUOZY/+Zi9lb4Tbza3BtuA==", + "requires": { + "@oclif/linewrap": "^1.0.0", + "chalk": "^2.4.2", + "tslib": "^1.9.3" + } + }, + "@oclif/plugin-help": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/@oclif/plugin-help/-/plugin-help-2.2.3.tgz", + "integrity": "sha512-bGHUdo5e7DjPJ0vTeRBMIrfqTRDBfyR5w0MP41u0n3r7YG5p14lvMmiCXxi6WDaP2Hw5nqx3PnkAIntCKZZN7g==", + "requires": { + "@oclif/command": "^1.5.13", + "chalk": "^2.4.1", + "indent-string": "^4.0.0", + "lodash.template": "^4.4.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0", + "widest-line": "^2.0.1", + "wrap-ansi": "^4.0.0" + }, + "dependencies": { + "indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==" + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + } + } + }, + "@oclif/screen": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@oclif/screen/-/screen-1.0.4.tgz", + "integrity": "sha512-60CHpq+eqnTxLZQ4PGHYNwUX572hgpMHGPtTWMjdTMsAvlm69lZV/4ly6O3sAYkomo4NggGcomrDpBe34rxUqw==" + }, + "@samverschueren/stream-to-observable": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@samverschueren/stream-to-observable/-/stream-to-observable-0.3.0.tgz", + "integrity": "sha512-MI4Xx6LHs4Webyvi6EbspgyAb4D2Q2VtnCQ1blOJcoLS6mVa8lNN2rkIy1CVxfTUpoyIbCTkXES1rLXztFD1lg==", + "requires": { + "any-observable": "^0.3.0" + } + }, + "@types/listr": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/@types/listr/-/listr-0.14.2.tgz", + "integrity": "sha512-wCipMbQr3t2UHTm90LldVp+oTBj1TX6zvpkCJcWS4o8nn6kS8SN93oUvKJAgueIRZ5M36yOlFmScqBxYH8Ajig==", + "requires": { + "@types/node": "*", + "rxjs": "^6.5.1" + } + }, + "@types/node": { + "version": "13.1.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.1.6.tgz", + "integrity": "sha512-Jg1F+bmxcpENHP23sVKkNuU3uaxPnsBMW0cLjleiikFKomJQbsn0Cqk2yDvQArqzZN6ABfBkZ0To7pQ8sLdWDg==" + }, + "accepts": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", + "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", + "requires": { + "mime-types": "~2.1.24", + "negotiator": "0.6.2" + } + }, + "ansi-escapes": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" + }, + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "ansicolors": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/ansicolors/-/ansicolors-0.3.2.tgz", + "integrity": "sha1-ZlWX3oap/+Oqm/vmyuXG6kJrSXk=" + }, + "any-observable": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/any-observable/-/any-observable-0.3.0.tgz", + "integrity": "sha512-/FQM1EDkTsf63Ub2C6O7GuYFDsSXUwsaZDurV0np41ocwq0jthUAYCmhBX9f+KwlaCgIuWyr/4WlUQUBfKfZog==" + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" + }, + "axios": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.1.tgz", + "integrity": "sha512-Yl+7nfreYKaLRvAvjNPkvfjnQHJM1yLBY3zhqAwcJSwR/6ETkanUgylgtIvkvz0xJ+p/vZuNw8X7Hnb7Whsbpw==", + "requires": { + "follow-redirects": "1.5.10" + } + }, + "body-parser": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", + "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", + "requires": { + "bytes": "3.1.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.2", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "on-finished": "~2.3.0", + "qs": "6.7.0", + "raw-body": "2.4.0", + "type-is": "~1.6.17" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "bytes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", + "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" + }, + "cardinal": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/cardinal/-/cardinal-2.1.1.tgz", + "integrity": "sha1-fMEFXYItISlU0HsIXeolHMe8VQU=", + "requires": { + "ansicolors": "~0.3.2", + "redeyed": "~2.1.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "clean-stack": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-1.3.0.tgz", + "integrity": "sha1-noIVAa6XmYbEax1m0tQy2y/UrjE=" + }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "requires": { + "restore-cursor": "^2.0.0" + } + }, + "cli-progress": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/cli-progress/-/cli-progress-3.5.0.tgz", + "integrity": "sha512-S1wR4xfcfLWbVBH6RwYat1nMCm2UsuygxNoiRYVAXQsuWKjCRgWRZVohXLmsWfiuAK0FFf7t9OyZ2JBmDWaQGA==", + "requires": { + "colors": "^1.1.2", + "string-width": "^2.1.1" + } + }, + "cli-truncate": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-0.2.1.tgz", + "integrity": "sha1-nxXPuwcFAFNpIWxiasfQWrkN1XQ=", + "requires": { + "slice-ansi": "0.0.4", + "string-width": "^1.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "cli-ux": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/cli-ux/-/cli-ux-5.4.1.tgz", + "integrity": "sha512-x5CJXJPKBrEo6o8Uy/Upajb9OWYMhTzOpRvKZyZ68kkHysiGd9phGP71WyHZfLUkhwdvpNUFkY2tsDr0ogyocg==", + "requires": { + "@oclif/command": "^1.5.1", + "@oclif/errors": "^1.2.1", + "@oclif/linewrap": "^1.0.0", + "@oclif/screen": "^1.0.3", + "ansi-escapes": "^3.1.0", + "ansi-styles": "^3.2.1", + "cardinal": "^2.1.1", + "chalk": "^2.4.1", + "clean-stack": "^2.0.0", + "cli-progress": "^3.4.0", + "extract-stack": "^1.0.0", + "fs-extra": "^7.0.1", + "hyperlinker": "^1.0.0", + "indent-string": "^4.0.0", + "is-wsl": "^1.1.0", + "js-yaml": "^3.13.1", + "lodash": "^4.17.11", + "natural-orderby": "^2.0.1", + "password-prompt": "^1.1.2", + "semver": "^5.6.0", + "string-width": "^3.1.0", + "strip-ansi": "^5.1.0", + "supports-color": "^5.5.0", + "supports-hyperlinks": "^1.0.1", + "treeify": "^1.1.0", + "tslib": "^1.9.3" + }, + "dependencies": { + "clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==" + }, + "indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==" + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + } + } + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=" + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==" + }, + "content-disposition": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", + "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "requires": { + "safe-buffer": "5.1.2" + } + }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" + }, + "cookie": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", + "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "date-fns": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-1.30.1.tgz", + "integrity": "sha512-hBSVCvSmWC+QypYObzwGOd9wqdDpOt+0wl0KbU+R+uuZBS1jN8VsD1ss3irQDknRj5NvxiTF6oj/nDRnN/UQNw==" + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "requires": { + "ms": "^2.1.1" + } + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + }, + "destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" + }, + "elegant-spinner": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/elegant-spinner/-/elegant-spinner-1.0.1.tgz", + "integrity": "sha1-2wQ1IcldfjA/2PNFvtwzSc+wcp4=" + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" + }, + "end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "requires": { + "once": "^1.4.0" + } + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" + }, + "execa": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.0.tgz", + "integrity": "sha512-JbDUxwV3BoT5ZVXQrSVbAiaXhXUkIwvbhPIwZ0N13kX+5yCzOhUNdocxB/UQRuYOHRYYwAxKYwJYc0T4D12pDA==", + "requires": { + "cross-spawn": "^7.0.0", + "get-stream": "^5.0.0", + "human-signals": "^1.1.1", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.0", + "onetime": "^5.1.0", + "signal-exit": "^3.0.2", + "strip-final-newline": "^2.0.0" + }, + "dependencies": { + "cross-spawn": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz", + "integrity": "sha512-u7v4o84SwFpD32Z8IIcPZ6z1/ie24O6RU3RbtL5Y316l3KuHVPx9ItBgWQ6VlfAFnRnTtMUrsQ9MUUTuEZjogg==", + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "express": { + "version": "4.17.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", + "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", + "requires": { + "accepts": "~1.3.7", + "array-flatten": "1.1.1", + "body-parser": "1.19.0", + "content-disposition": "0.5.3", + "content-type": "~1.0.4", + "cookie": "0.4.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.1.2", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.5", + "qs": "6.7.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.1.2", + "send": "0.17.1", + "serve-static": "1.14.1", + "setprototypeof": "1.1.1", + "statuses": "~1.5.0", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "extract-stack": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/extract-stack/-/extract-stack-1.0.0.tgz", + "integrity": "sha1-uXrK+UQe6iMyUpYktzL8WhyBZfo=" + }, + "figures": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", + "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", + "requires": { + "escape-string-regexp": "^1.0.5", + "object-assign": "^4.1.0" + } + }, + "finalhandler": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", + "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "follow-redirects": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", + "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", + "requires": { + "debug": "=3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "forwarded": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", + "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" + }, + "fs-extra": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", + "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "get-stream": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.1.0.tgz", + "integrity": "sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw==", + "requires": { + "pump": "^3.0.0" + } + }, + "graceful-fs": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", + "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==" + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "requires": { + "ansi-regex": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + } + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "http-errors": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", + "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", + "requires": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.1", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.0" + } + }, + "human-signals": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz", + "integrity": "sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==" + }, + "hyperlinker": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/hyperlinker/-/hyperlinker-1.0.0.tgz", + "integrity": "sha512-Ty8UblRWFEcfSuIaajM34LdPXIhbs1ajEX/BBPv24J+enSVaEVY63xQ6lTO9VRYS5LAoghIG0IDJ+p+IPzKUQQ==" + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "indent-string": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", + "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=" + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "ipaddr.js": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.0.tgz", + "integrity": "sha512-M4Sjn6N/+O6/IXSJseKqHoFc+5FdGJ22sXqnjTpdZweHK64MzEPAyQZyEU3R/KRv2GLoa7nNtg/C2Ev6m7z+eA==" + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" + }, + "is-observable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-observable/-/is-observable-1.1.0.tgz", + "integrity": "sha512-NqCa4Sa2d+u7BWc6CukaObG3Fh+CU9bvixbpcXYhy2VvYS7vVGIdAgnIS5Ks3A/cqk4rebLJ9s8zBstT2aKnIA==", + "requires": { + "symbol-observable": "^1.1.0" + } + }, + "is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", + "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=" + }, + "is-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==" + }, + "is-wsl": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", + "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=" + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" + }, + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "kuzdoc": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/kuzdoc/-/kuzdoc-1.2.2.tgz", + "integrity": "sha512-QXw4dVIh4dRoD/9Vz9tbpfKNT9Y0AEORJyRHIwKuHaxH65Ccr7KHwxSTbJokK/PV4PebRDO96sPodEc/4NrxbQ==", + "requires": { + "@oclif/command": "^1.5.19", + "@oclif/config": "^1.13.3", + "@oclif/plugin-help": "^2.2.3", + "@types/listr": "^0.14.2", + "axios": "^0.19.0", + "cli-ux": "^5.4.1", + "execa": "^4.0.0", + "express": "^4.17.1", + "listr": "^0.14.3", + "tslib": "^1.10.0", + "yaml": "^1.7.2" + } + }, + "listr": { + "version": "0.14.3", + "resolved": "https://registry.npmjs.org/listr/-/listr-0.14.3.tgz", + "integrity": "sha512-RmAl7su35BFd/xoMamRjpIE4j3v+L28o8CT5YhAXQJm1fD+1l9ngXY8JAQRJ+tFK2i5njvi0iRUKV09vPwA0iA==", + "requires": { + "@samverschueren/stream-to-observable": "^0.3.0", + "is-observable": "^1.1.0", + "is-promise": "^2.1.0", + "is-stream": "^1.1.0", + "listr-silent-renderer": "^1.1.1", + "listr-update-renderer": "^0.5.0", + "listr-verbose-renderer": "^0.5.0", + "p-map": "^2.0.0", + "rxjs": "^6.3.3" + }, + "dependencies": { + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" + } + } + }, + "listr-silent-renderer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/listr-silent-renderer/-/listr-silent-renderer-1.1.1.tgz", + "integrity": "sha1-kktaN1cVN3C/Go4/v3S4u/P5JC4=" + }, + "listr-update-renderer": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/listr-update-renderer/-/listr-update-renderer-0.5.0.tgz", + "integrity": "sha512-tKRsZpKz8GSGqoI/+caPmfrypiaq+OQCbd+CovEC24uk1h952lVj5sC7SqyFUm+OaJ5HN/a1YLt5cit2FMNsFA==", + "requires": { + "chalk": "^1.1.3", + "cli-truncate": "^0.2.1", + "elegant-spinner": "^1.0.1", + "figures": "^1.7.0", + "indent-string": "^3.0.0", + "log-symbols": "^1.0.2", + "log-update": "^2.3.0", + "strip-ansi": "^3.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" + } + } + }, + "listr-verbose-renderer": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/listr-verbose-renderer/-/listr-verbose-renderer-0.5.0.tgz", + "integrity": "sha512-04PDPqSlsqIOaaaGZ+41vq5FejI9auqTInicFRndCBgE3bXG8D6W1I+mWhk+1nqbHmyhla/6BUrd5OSiHwKRXw==", + "requires": { + "chalk": "^2.4.1", + "cli-cursor": "^2.1.0", + "date-fns": "^1.27.2", + "figures": "^2.0.0" + }, + "dependencies": { + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "requires": { + "escape-string-regexp": "^1.0.5" + } + } + } + }, + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" + }, + "lodash._reinterpolate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", + "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=" + }, + "lodash.template": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-4.5.0.tgz", + "integrity": "sha512-84vYFxIkmidUiFxidA/KjjH9pAycqW+h980j7Fuz5qxRtO9pgB7MDFTdys1N7A5mcucRiDyEq4fusljItR1T/A==", + "requires": { + "lodash._reinterpolate": "^3.0.0", + "lodash.templatesettings": "^4.0.0" + } + }, + "lodash.templatesettings": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-4.2.0.tgz", + "integrity": "sha512-stgLz+i3Aa9mZgnjr/O+v9ruKZsPsndy7qPZOchbqk2cnTU1ZaldKK+v7m54WoKIyxiuMZTKT2H81F8BeAc3ZQ==", + "requires": { + "lodash._reinterpolate": "^3.0.0" + } + }, + "log-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-1.0.2.tgz", + "integrity": "sha1-N2/3tY6jCGoPCfrMdGF+ylAeGhg=", + "requires": { + "chalk": "^1.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" + } + } + }, + "log-update": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-2.3.0.tgz", + "integrity": "sha1-iDKP19HOeTiykoN0bwsbwSayRwg=", + "requires": { + "ansi-escapes": "^3.0.0", + "cli-cursor": "^2.0.0", + "wrap-ansi": "^3.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + }, + "wrap-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-3.0.1.tgz", + "integrity": "sha1-KIoE2H7aXChuBg3+jxNc6NAH+Lo=", + "requires": { + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0" + } + } + } + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" + }, + "merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" + }, + "mime-db": { + "version": "1.43.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.43.0.tgz", + "integrity": "sha512-+5dsGEEovYbT8UY9yD7eE4XTc4UwJ1jBYlgaQQF38ENsKR3wj/8q8RFZrF9WIZpB2V1ArTVFUva8sAul1NzRzQ==" + }, + "mime-types": { + "version": "2.1.26", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.26.tgz", + "integrity": "sha512-01paPWYgLrkqAyrlDorC1uDwl2p3qZT7yl806vW7DvDoxwXi46jsjFbg+WdwotBIk6/MbEhO/dh5aZ5sNj/dWQ==", + "requires": { + "mime-db": "1.43.0" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "natural-orderby": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/natural-orderby/-/natural-orderby-2.0.3.tgz", + "integrity": "sha512-p7KTHxU0CUrcOXe62Zfrb5Z13nLvPhSWR/so3kFulUQU0sgUll2Z0LwpsLN351eOOD+hRGu/F1g+6xDfPeD++Q==" + }, + "negotiator": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", + "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==" + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "requires": { + "path-key": "^3.0.0" + }, + "dependencies": { + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" + } + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" + }, + "on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "requires": { + "ee-first": "1.1.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz", + "integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==", + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "p-map": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.1.0.tgz", + "integrity": "sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==" + }, + "parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" + }, + "password-prompt": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/password-prompt/-/password-prompt-1.1.2.tgz", + "integrity": "sha512-bpuBhROdrhuN3E7G/koAju0WjVw9/uQOG5Co5mokNj0MiOSBVZS1JTwM4zl55hu0WFmIEFvO9cU9sJQiBIYeIA==", + "requires": { + "ansi-escapes": "^3.1.0", + "cross-spawn": "^6.0.5" + } + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" + }, + "path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" + }, + "proxy-addr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.5.tgz", + "integrity": "sha512-t/7RxHXPH6cJtP0pRG6smSr9QJidhB+3kXu0KgXnbGYMgzEnUxRQ4/LDdfOwZEMyIh3/xHb8PX3t+lfL9z+YVQ==", + "requires": { + "forwarded": "~0.1.2", + "ipaddr.js": "1.9.0" + } + }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "qs": { + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", + "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==" + }, + "range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" + }, + "raw-body": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", + "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", + "requires": { + "bytes": "3.1.0", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + } + }, + "redeyed": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/redeyed/-/redeyed-2.1.1.tgz", + "integrity": "sha1-iYS1gV2ZyyIEacme7v/jiRPmzAs=", + "requires": { + "esprima": "~4.0.0" + } + }, + "regenerator-runtime": { + "version": "0.13.3", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.3.tgz", + "integrity": "sha512-naKIZz2GQ8JWh///G7L3X6LaQUAMp2lvb1rvwwsURe/VXwD6VMfr+/1NuNw3ag8v2kY1aQ/go5SNn79O9JU7yw==" + }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + }, + "dependencies": { + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==" + }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "requires": { + "mimic-fn": "^1.0.0" + } + } + } + }, + "rxjs": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.4.tgz", + "integrity": "sha512-naMQXcgEo3csAEGvw/NydRA0fuS2nDZJiw1YUWFKU7aPPAPGZEsD4Iimit96qwCieH6y614MCLYwdkrWx7z/7Q==", + "requires": { + "tslib": "^1.9.0" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "send": { + "version": "0.17.1", + "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", + "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", + "requires": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.7.2", + "mime": "1.6.0", + "ms": "2.1.1", + "on-finished": "~2.3.0", + "range-parser": "~1.2.1", + "statuses": "~1.5.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + } + } + }, + "serve-static": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", + "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", + "requires": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.17.1" + } + }, + "setprototypeof": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", + "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" + }, + "slice-ansi": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-0.0.4.tgz", + "integrity": "sha1-7b+JA/ZvfOL46v1s7tZeJkyDGzU=" + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" + }, + "statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=" + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==" + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "supports-hyperlinks": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-1.0.1.tgz", + "integrity": "sha512-HHi5kVSefKaJkGYXbDuKbUGRVxqnWGn3J2e39CYcNJEfWciGq2zYtOhXLTlvrOZW1QU7VX67w7fMmWafHX9Pfw==", + "requires": { + "has-flag": "^2.0.0", + "supports-color": "^5.0.0" + }, + "dependencies": { + "has-flag": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", + "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=" + } + } + }, + "symbol-observable": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.2.0.tgz", + "integrity": "sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==" + }, + "toidentifier": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", + "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==" + }, + "treeify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/treeify/-/treeify-1.1.0.tgz", + "integrity": "sha512-1m4RA7xVAJrSGrrXGs0L3YTwyvBs2S8PbRHaLZAkFw7JR8oIFwYtysxlBZhYIa7xSyiYJKZ3iGrrk55cGA3i9A==" + }, + "tslib": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz", + "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==" + }, + "type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + } + }, + "universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "requires": { + "isexe": "^2.0.0" + } + }, + "widest-line": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-2.0.1.tgz", + "integrity": "sha512-Ba5m9/Fa4Xt9eb2ELXt77JxVDV8w7qQrH0zS/TWSJdLyAwQjWoOzpzj5lwVftDz6n/EOu3tNACS84v509qwnJA==", + "requires": { + "string-width": "^2.1.1" + } + }, + "wrap-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-4.0.0.tgz", + "integrity": "sha512-uMTsj9rDb0/7kk1PbcbCcwvHUxp60fGDB/NNXpVa0Q+ic/e7y5+BwTxKfQ33VYgDppSwi/FBzpetYzo8s6tfbg==", + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "yaml": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.7.2.tgz", + "integrity": "sha512-qXROVp90sb83XtAoqE8bP9RwAkTTZbugRUTm5YeFCBfNRPEp2YzTeqWiz7m5OORHzEvrA/qcGS8hp/E+MMROYw==", + "requires": { + "@babel/runtime": "^7.6.3" + } + } + } +} diff --git a/package.json b/package.json index c460343a..6703ff8e 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,15 @@ { "name": "sdk-java", "scripts": { - "doc-prepare": "cd doc && bash doc.sh prepare", - "doc-dev": "cd doc && bash doc.sh dev", - "doc-build": "cd doc && bash doc.sh build", - "doc-upload": "cd doc && bash doc.sh upload", - "doc-cloudfront": "cd doc && bash doc.sh cloudfront", + "doc-prepare": "kuzdoc framework:install", + "doc-dev": "kuzdoc repo:dev -d /sdk/java/3/ -v 3", + "doc-build": "kuzdoc repo:build -d /sdk/java/3/ -v 3", + "doc-upload": "kuzdoc repo:deploy -d /sdk/java/3/ -v 3", + "doc-cloudfront": "kuzdoc repo:cloudfront -d /sdk/java/3/", "doc-deploy": "npm run doc-upload && npm run doc-cloudfront", - "doc-netlify": "npm run doc-prepare && cd doc && bash doc.sh build-netlify" + "doc-netlify": "npm run doc-prepare && kuzdoc repo:build -d / -v 3" + }, + "dependencies": { + "kuzdoc": "^1.2.2" } -} \ No newline at end of file +} diff --git a/settings.gradle b/settings.gradle index 7b986f12..e71b73bc 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,10 +1 @@ -/* - * This file was generated by the Gradle 'init' task. - * - * The settings file is used to specify which projects to include in your build. - * - * Detailed information about configuring a multi-project build in Gradle can be found - * in the user guide at https://docs.gradle.org/4.5.1/userguide/multi_project_builds.html - */ - rootProject.name = 'sdk-java' diff --git a/src/main/java/io/kuzzle/sdk/API/Controllers/AuthController.java b/src/main/java/io/kuzzle/sdk/API/Controllers/AuthController.java new file mode 100644 index 00000000..318aff2b --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/API/Controllers/AuthController.java @@ -0,0 +1,273 @@ +package io.kuzzle.sdk.API.Controllers; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; + +import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; + +public class AuthController extends BaseController { + + public AuthController(final Kuzzle kuzzle) { + super(kuzzle); + } + + /** + * Checks the validity of an authentication token. + * + * @param token An authentication token + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> checkToken( + final String token) throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "checkToken") + .put("body", new KuzzleMap().put("token", token)); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Creates new credentials for the current user. + * + * @param strategy A String representing the strategy + * @param credentials A ConcurrentHashMap representing + * credentials information + * @return A CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> createMyCredentials( + final String strategy, + final ConcurrentHashMap credentials) + throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "createMyCredentials") + .put("body", credentials) + .put("strategy", strategy); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> KuzzleMap + .from((ConcurrentHashMap) response.result)); + } + + /** + * Checks that the current authenticated user has credentials for the + * specified authentication strategy. + * + * @param strategy A String representing the strategy + * @return A CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture credentialsExist(final String strategy) + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "credentialsExist") + .put("strategy", strategy); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> (Boolean) response.result); + } + + public CompletableFuture deleteMyCredentials(final String strategy) + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query.put("controller", "auth"); + query.put("action", "deleteMyCredentials"); + query.put("strategy", strategy); + + return kuzzle.query(query).thenRunAsync(() -> { + }); + } + + public CompletableFuture> getCurrentUser() + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query.put("controller", "auth").put("action", "getCurrentUser"); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> KuzzleMap + .from((ConcurrentHashMap) response.result)); + } + + public CompletableFuture> getMyCredentials( + final String strategy) throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "getMyCredentials") + .put("strategy", strategy); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> KuzzleMap + .from((ConcurrentHashMap) response.result)); + } + + public CompletableFuture> getMyRights() + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query.put("controller", "auth").put("action", "getMyRights"); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> KuzzleMap + .from((ConcurrentHashMap) response.result) + .getArrayList("hits")); + } + + public CompletableFuture> getStrategies() + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query.put("controller", "auth") + .put("action", "getStrategies"); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> (ArrayList) response.result); + } + + public CompletableFuture> login( + final String strategy, + final ConcurrentHashMap credentials, + final String expiresIn) throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "login") + .put("strategy", strategy) + .put("body", credentials) + .put("expiresIn", expiresIn); + + return kuzzle.query(query).thenApplyAsync((response) -> { + final KuzzleMap map = KuzzleMap + .from((ConcurrentHashMap) response.result); + kuzzle.setAuthenticationToken(map.getString("jwt")); + if (map.getString("_id") != null) { + kuzzle.trigger(Event.loginAttempt, true); + } else { + kuzzle.trigger(Event.loginAttempt, false); + } + return map; + }); + } + + public CompletableFuture> login( + final String strategy, + final ConcurrentHashMap credentials) + throws NotConnectedException, InternalException { + return login(strategy, credentials, null); + } + + public CompletableFuture logout() + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query.put("controller", "auth").put("action", "logout"); + + return kuzzle.query(query); + } + + public CompletableFuture> refreshToken( + final String expiresIn) throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "refreshToken") + .put("expiresIn", expiresIn); + + return kuzzle.query(query).thenApplyAsync((response) -> { + final KuzzleMap map = KuzzleMap + .from((ConcurrentHashMap) response.result); + kuzzle.setAuthenticationToken(map.getString("jwt")); + + return map; + }); + } + + public CompletableFuture> refreshToken() + throws NotConnectedException, InternalException { + return refreshToken(null); + } + + public CompletableFuture> updateMyCredentials( + final String strategy, + final ConcurrentHashMap credentials) + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "updateMyCredentials") + .put("strategy", strategy) + .put("body", credentials); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> KuzzleMap + .from((ConcurrentHashMap) response.result)); + } + + public CompletableFuture> updateSelf( + final ConcurrentHashMap content) + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "updateSelf") + .put("body", content); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> KuzzleMap + .from((ConcurrentHashMap) response.result)); + } + + public CompletableFuture validateMyCredentials(final String strategy, + final ConcurrentHashMap credentials) + throws NotConnectedException, InternalException { + final KuzzleMap query = new KuzzleMap(); + + query + .put("controller", "auth") + .put("action", "validateMyCredentials") + .put("strategy", strategy) + .put("body", credentials); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> (Boolean) response.result); + } +} diff --git a/src/main/java/io/kuzzle/sdk/API/Controllers/BaseController.java b/src/main/java/io/kuzzle/sdk/API/Controllers/BaseController.java new file mode 100644 index 00000000..ea16442a --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/API/Controllers/BaseController.java @@ -0,0 +1,12 @@ + +package io.kuzzle.sdk.API.Controllers; + +import io.kuzzle.sdk.Kuzzle; + +public class BaseController { + protected final Kuzzle kuzzle; + + protected BaseController(Kuzzle kuzzle) { + this.kuzzle = kuzzle; + } +} diff --git a/src/main/java/io/kuzzle/sdk/API/Controllers/CollectionController.java b/src/main/java/io/kuzzle/sdk/API/Controllers/CollectionController.java new file mode 100644 index 00000000..0c6c6963 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/API/Controllers/CollectionController.java @@ -0,0 +1,352 @@ +package io.kuzzle.sdk.API.Controllers; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.SearchResult; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Options.SearchOptions; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; + +public class CollectionController extends BaseController { + + public CollectionController(final Kuzzle kuzzle) { + super(kuzzle); + } + + /** + * Tells if a collection exists in a given index. + * + * @param index + * @param collection + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture exists( + final String index, + final String collection) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "exists"); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (Boolean) response.result); + } + + /** + * Removes all documents from collection. + * + * @param index + * @param collection + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture truncate( + final String index, + final String collection) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "truncate"); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (null)); + } + + /** + * Creates a collection in a given index. + * + * @param index + * @param collection + * @param mappings + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture create( + final String index, + final String collection, + final ConcurrentHashMap mappings) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "create") + .put("body", mappings != null ? new KuzzleMap(mappings) : null); + + return kuzzle + .query(query) + .thenApplyAsync((response) -> null); + } + + /** + * Creates a collection in a given index. + * + * @param index + * @param collection + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture create( + final String index, + final String collection) throws NotConnectedException, InternalException { + + return this.create(index, collection, null); + } + + /** + * Get collection mapping + * + * @param index + * @param collection + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> getMapping( + final String index, + final String collection) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "getMapping"); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Refreshes collection. + * + * @param index + * @param collection + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture refresh( + final String index, + final String collection) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "refresh"); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> null); + } + + /** + * Deletes the validation specifications associated to the given index and collection. + * + * @param index + * @param collection + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture deleteSpecifications( + final String index, + final String collection) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "deleteSpecifications"); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> null); + } + + /** + * Gets the validation specifications associated to the given index and collection. + * + * @param index + * @param collection + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> getSpecifications( + final String index, + final String collection) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "getSpecifications"); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Validates specifications for a collection. + * + * @param index + * @param collection + * @param specifications + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> validateSpecifications( + final String index, + final String collection, + final ConcurrentHashMap specifications) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "validateSpecifications") + .put("body", new KuzzleMap(specifications)); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Updates validation specifications for a collection. + * + * @param index + * @param collection + * @param specifications + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> updateSpecifications( + final String index, + final String collection, + final ConcurrentHashMap specifications) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "collection") + .put("action", "updateSpecifications") + .put("body", new KuzzleMap(specifications)); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Searches collection specifications. + * + * @param searchQuery + * @param options + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture searchSpecifications( + final ConcurrentHashMap searchQuery, + final SearchOptions options) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("controller", "collection") + .put("action", "searchSpecifications") + .put("body", new KuzzleMap(searchQuery)); + + if (options != null) { + query + .put("from", options.getFrom()) + .put("size", options.getSize()); + if (options.getScroll() != null) { + query.put("scroll", options.getScroll()); + } + } + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> new SearchResult(kuzzle, query, options, response)); + } + + /** + * Searches collection specifications. + * + * @param searchQuery + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture searchSpecifications( + final ConcurrentHashMap searchQuery) throws NotConnectedException, InternalException { + + return this.searchSpecifications(searchQuery, null); + } + + /** + * List collections. + * + * @param index + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> list( + final String index) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("controller", "collection") + .put("action", "list"); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } +} diff --git a/src/main/java/io/kuzzle/sdk/API/Controllers/DocumentController.java b/src/main/java/io/kuzzle/sdk/API/Controllers/DocumentController.java new file mode 100644 index 00000000..e2b4a945 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/API/Controllers/DocumentController.java @@ -0,0 +1,914 @@ +package io.kuzzle.sdk.API.Controllers; + +import com.google.gson.internal.LazilyParsedNumber; +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.CoreClasses.SearchResult; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Options.SearchOptions; +import io.kuzzle.sdk.Options.UpdateOptions; +import io.kuzzle.sdk.Options.CreateOptions; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; + +public class DocumentController extends BaseController { + public DocumentController(final Kuzzle kuzzle) { + super(kuzzle); + } + + /** + * Creates a document in a given collection and index. + * + * @param index + * @param collection + * @param document + * @param options + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> create( + final String index, + final String collection, + final ConcurrentHashMap document, + final CreateOptions options) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + String id = null; + Boolean waitForRefresh = null; + if (options != null) { + waitForRefresh = options.getWaitForRefresh(); + id = options.getId(); + } + + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "create") + .put("body", document) + .put("_id", id) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Creates a document in a given collection and index. + * + * @param index + * @param collection + * @param document + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> create( + final String index, + final String collection, + final ConcurrentHashMap document) throws NotConnectedException, InternalException { + + return this.create(index, collection, document, null); + } + + /** + * Updates a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @param document + * @param options + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> update( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document, + final UpdateOptions options) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + Integer retryOnConflict = null; + Boolean waitForRefresh = null; + Boolean source = null; + if (options != null) { + retryOnConflict = options.getRetryOnConflict(); + source = options.getSource(); + waitForRefresh = options.getWaitForRefresh(); + } + + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "update") + .put("body", document) + .put("_id", id) + .put("waitForRefresh", waitForRefresh) + .put("retryOnConflict", retryOnConflict) + .put("source", source); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Updates a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @param document + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> update( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document) throws NotConnectedException, InternalException { + + return this.update(index, collection, id, document, null); + } + + /** + * Gets a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> get( + final String index, + final String collection, + final String id) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "get") + .put("_id", id); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Creates or Replace a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @param document + * @param waitForRefresh + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> createOrReplace( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document, + final Boolean waitForRefresh) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "createOrReplace") + .put("body", document) + .put("_id", id) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Creates or Replace a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @param document + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> createOrReplace( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document) throws NotConnectedException, InternalException { + + return this.createOrReplace(index, collection, id, document, null); + } + + /** + * Creates multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param documents + * @param waitForRefresh + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mCreate( + final String index, + final String collection, + final ArrayList> documents, + final Boolean waitForRefresh) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "mCreate") + .put("body", new KuzzleMap().put("documents", documents)) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap>) response.result); + } + + /** + * Creates multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param documents + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mCreate( + final String index, + final String collection, + final ArrayList> documents) throws NotConnectedException, InternalException { + + return this.mCreate(index, collection, documents, null); + } + + /** + * Deletes multiple documents. + * + * @param index + * @param collection + * @param ids + * @param waitForRefresh + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mDelete( + final String index, + final String collection, + final ArrayList ids, + final Boolean waitForRefresh) throws NotConnectedException, InternalException { + + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "mDelete") + .put("waitForRefresh", waitForRefresh) + .put("body", new KuzzleMap().put("ids", ids)); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap>) response.result); + } + + /** + * Deletes multiple documents. + * + * @param index + * @param collection + * @param ids + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mDelete( + final String index, + final String collection, + final ArrayList ids) throws NotConnectedException, InternalException { + + return mDelete(index, collection, ids, null); + } + + /** + * Replace a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @param document + * @param waitForRefresh + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> replace( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document, + final Boolean waitForRefresh) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "replace") + .put("body", document) + .put("_id", id) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Replace a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @param document + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> replace( + final String index, + final String collection, + final String id, + final ConcurrentHashMap document) throws NotConnectedException, InternalException { + + return this.replace(index, collection, id, document, null); + } + + /** + * Deletes a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @param waitForRefresh + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> delete( + final String index, + final String collection, + final String id, + final Boolean waitForRefresh) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "delete") + .put("_id", id) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap) response.result); + } + + /** + * Deletes a document in a given collection and index. + * + * @param index + * @param collection + * @param id + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> delete( + final String index, + final String collection, + final String id) throws NotConnectedException, InternalException { + + return this.delete(index, collection, id, null); + } + + /** + * Gets multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param ids + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mGet( + final String index, + final String collection, + final ArrayList ids) throws NotConnectedException, InternalException { + + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "mGet") + .put("body", new KuzzleMap().put("ids", ids)); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap>) response.result); + } + + /** + * Replaces multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param documents + * @param waitForRefresh + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mReplace( + final String index, + final String collection, + final ArrayList> documents, + final Boolean waitForRefresh) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "mReplace") + .put("body", new KuzzleMap().put("documents", documents)) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap>) response.result); + } + + /** + * Replaces multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param documents + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mReplace( + final String index, + final String collection, + final ArrayList> documents) throws NotConnectedException, InternalException { + + return this.mReplace(index, collection, documents, null); + } + + /** + * Tells if a document exists in a given collection and index. + * + * @param index + * @param collection + * @param id + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture exists( + final String index, + final String collection, + final String id) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "exists") + .put("_id", id); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (Boolean) response.result); + } + + /** + * Updates multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param documents + * @param options + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mUpdate( + final String index, + final String collection, + final ArrayList> documents, + final UpdateOptions options) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + Integer retryOnConflict = null; + Boolean waitForRefresh = null; + if (options != null) { + retryOnConflict = options.getRetryOnConflict(); + waitForRefresh = options.getWaitForRefresh(); + } + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "mUpdate") + .put("body", new KuzzleMap().put("documents", documents)) + .put("retryOnConflict", retryOnConflict) + .put("waitForRefresh", waitForRefresh); + + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap>) response.result); + } + + /** + * Updates multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param documents + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mUpdate( + final String index, + final String collection, + final ArrayList> documents) throws NotConnectedException, InternalException { + + return this.mUpdate(index, collection, documents, null); + } + + /** + * Creates or replaces multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param documents + * @param waitForRefresh + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mCreateOrReplace( + final String index, + final String collection, + final ArrayList> documents, + final Boolean waitForRefresh) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "mCreateOrReplace") + .put("body", new KuzzleMap().put("documents", documents)) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap>) response.result); + } + + /** + * Creates or replaces multiple documents in a given collection and index. + * + * @param index + * @param collection + * @param documents + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> mCreateOrReplace( + final String index, + final String collection, + final ArrayList> documents) throws NotConnectedException, InternalException { + + return this.mCreateOrReplace(index, collection, documents, null); + } + + /** + * Deletes documents matching the provided search query. + * + * @param index + * @param collection + * @param searchQuery + * @param waitForRefresh + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> deleteByQuery( + final String index, + final String collection, + final ConcurrentHashMap searchQuery, + final Boolean waitForRefresh) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "deleteByQuery") + .put("body", new KuzzleMap(searchQuery)) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ArrayList) ((ConcurrentHashMap) response.result).get("ids")); + } + + /** + * Deletes documents matching the provided search query. + * + * @param index + * @param collection + * @param searchQuery + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> deleteByQuery( + final String index, + final String collection, + final ConcurrentHashMap searchQuery) throws NotConnectedException, InternalException { + + return this.deleteByQuery(index, collection, searchQuery, null); + } + + /** + * Validates data against existing validation rules. + * + * @param index + * @param collection + * @param document + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture validate( + final String index, + final String collection, + final ConcurrentHashMap document) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "validate") + .put("body", new KuzzleMap(document)); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (Boolean) ((ConcurrentHashMap) response.result).get("valid")); + } + + /** + * Counts documents in a collection. + * + * @param index + * @param collection + * @param searchQuery + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture count( + final String index, + final String collection, + final ConcurrentHashMap searchQuery) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("body", new KuzzleMap().put("query", searchQuery)) + .put("action", "count"); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> ((LazilyParsedNumber) ((ConcurrentHashMap) response.result).get("count")).intValue()); + } + + /** + * Counts documents in a collection. + * + * @param index + * @param collection + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture count( + final String index, + final String collection) throws NotConnectedException, InternalException { + + final ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + + return this.count(index, collection, searchQuery); + } + + /** + * Updates documents matching the provided search query. + * + * @param index + * @param collection + * @param searchQuery + * @param changes + * @param options + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> updateByQuery( + final String index, + final String collection, + final ConcurrentHashMap searchQuery, + final ConcurrentHashMap changes, + final UpdateOptions options) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + + Integer retryOnConflict = null; + Boolean waitForRefresh = null; + Boolean source = null; + + if (options != null) { + retryOnConflict = options.getRetryOnConflict(); + source = options.getSource(); + waitForRefresh = options.getWaitForRefresh(); + } + + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "updateByQuery") + .put("body", new KuzzleMap() + .put("query", searchQuery) + .put("changes", changes)) + .put("source", source) + .put("retryOnConflict", retryOnConflict) + .put("waitForRefresh", waitForRefresh); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> (ConcurrentHashMap>) response.result); + } + + /** + * Updates documents matching the provided search query. + * + * @param index + * @param collection + * @param searchQuery + * @param changes + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture>> updateByQuery( + final String index, + final String collection, + final ConcurrentHashMap searchQuery, + final ConcurrentHashMap changes) throws NotConnectedException, InternalException { + + return this.updateByQuery(index, collection, searchQuery, changes, null); + } + + /** + * Searches documents. + * + * @param index + * @param collection + * @param searchQuery + * @param options + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture search( + final String index, + final String collection, + final ConcurrentHashMap searchQuery, + final SearchOptions options) throws NotConnectedException, InternalException { + + final KuzzleMap query = new KuzzleMap(); + query + .put("index", index) + .put("collection", collection) + .put("controller", "document") + .put("action", "search") + .put("body", new KuzzleMap(searchQuery)); + + if (options != null) { + query + .put("from", options.getFrom()) + .put("size", options.getSize()); + if (options.getScroll() != null) { + query.put("scroll", options.getScroll()); + } + } + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> new SearchResult(kuzzle, query, options, response)); + } + + /** + * Searches documents. + * + * @param index + * @param collection + * @param searchQuery + * @return a CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture search( + final String index, + final String collection, + final ConcurrentHashMap searchQuery) throws NotConnectedException, InternalException { + + return this.search(index, collection, searchQuery, new SearchOptions()); + } +} diff --git a/src/main/java/io/kuzzle/sdk/API/Controllers/IndexController.java b/src/main/java/io/kuzzle/sdk/API/Controllers/IndexController.java new file mode 100644 index 00000000..71c529c9 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/API/Controllers/IndexController.java @@ -0,0 +1,98 @@ +package io.kuzzle.sdk.API.Controllers; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; + +import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; + +public class IndexController extends BaseController { + public IndexController(final Kuzzle kuzzle) { + super(kuzzle); + } + + /** + * Creates a new index in Kuzzle via the persistence engine. + * + * @param index + * @return A CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture create(final String index) throws NotConnectedException, InternalException { + return kuzzle + .query(new KuzzleMap() + .put("controller", "index") + .put("action", "create") + .put("index", index)) + .thenApplyAsync((response) -> null); + } + + /** + * Deletes an index in Kuzzle via the persistence engine. + * + * @param index + * @return A CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture delete(final String index) throws NotConnectedException, InternalException { + return kuzzle + .query(new KuzzleMap() + .put("controller", "index") + .put("action", "delete") + .put("index", index)) + .thenApplyAsync((response) -> null); + } + + /** + * Checks if an index exists in the Kuzzle persistence engine. + * + * @param index + * @return A CompletableFuture + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture exists(final String index) throws NotConnectedException, InternalException { + return kuzzle + .query(new KuzzleMap() + .put("controller", "index") + .put("action", "exists") + .put("index", index)) + .thenApplyAsync((response) -> (Boolean) response.result); + } + + /** + * Lists indexes from the Kuzzle persistence engine. + * + * @return A CompletableFuture> + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> list() throws NotConnectedException, InternalException { + return kuzzle + .query(new KuzzleMap() + .put("controller", "index") + .put("action", "list")) + .thenApplyAsync((response) -> (((KuzzleMap) response.result).getArrayList("indexes"))); + } + + /** + * Deletes multiple indexes from the Kuzzle persistence engine. + * + * @param indexes + * @return A CompletableFuture> + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture> mDelete(final ArrayList indexes) throws NotConnectedException, InternalException { + return kuzzle + .query(new KuzzleMap() + .put("controller", "index") + .put("action", "mDelete") + .put("body", new KuzzleMap().put("indexes", indexes))) + .thenApplyAsync((response) -> (((KuzzleMap) response.result).getArrayList("deleted"))); + } +} diff --git a/src/main/java/io/kuzzle/sdk/API/Controllers/RealtimeController.java b/src/main/java/io/kuzzle/sdk/API/Controllers/RealtimeController.java new file mode 100644 index 00000000..acdc03b6 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/API/Controllers/RealtimeController.java @@ -0,0 +1,227 @@ +package io.kuzzle.sdk.API.Controllers; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Handlers.NotificationHandler; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Options.SubscribeOptions; +import io.kuzzle.sdk.Protocol.ProtocolState; + +import java.util.ArrayList; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; + +public class RealtimeController extends BaseController { + private class Subscription { + public String index; + public String collection; + public ConcurrentHashMap filter; + public NotificationHandler handler; + public SubscribeOptions options; + + public Subscription(final String index, + final String collection, + final ConcurrentHashMap filter, + final NotificationHandler handler, + final SubscribeOptions options) { + this.index = index; + this.collection = collection; + this.filter = filter; + this.handler = handler; + this.options = (options != null ? options : new SubscribeOptions()); + } + } + + private ConcurrentHashMap> currentSubscriptions = new ConcurrentHashMap<>(); + private ConcurrentHashMap> subscriptionsCache = new ConcurrentHashMap<>(); + + public RealtimeController(Kuzzle kuzzle) { + super(kuzzle); + kuzzle.register(Event.unhandledResponse, args -> { + Response response = (Response) args[0]; + + if (response.error != null && response.error.id.equals("security.token.expired")) { + kuzzle.trigger(Event.tokenExpired); + return; + } + + String sdkInstanceId = ""; + if (response.Volatile != null) { + sdkInstanceId = response.Volatile.get("sdkInstanceId").toString(); + } + + ArrayList subs = RealtimeController.this.currentSubscriptions.get(((Response) args[0]).room); + + if (subs != null) { + final String instanceId = sdkInstanceId; + subs.forEach(sub -> { + if (sub != null && (instanceId.equals(kuzzle.instanceId) && sub.options.isSubscribeToSelf() || !instanceId.equals(kuzzle.instanceId))) { + sub.handler.run(response); + } + }); + } + }); + kuzzle.register(Event.networkStateChange, state -> { + if (state[0] == ProtocolState.CLOSE) { + this.currentSubscriptions.clear(); + } + }); + } + + /** + * Returns the number of other connections sharing the same subscription. + * + * @param roomId + * @return + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture count(final String roomId) throws NotConnectedException, InternalException { + return kuzzle + .query(new KuzzleMap() + .put("controller", "realtime") + .put("action", "count") + .put("body", new KuzzleMap().put("roomId", roomId))) + .thenApplyAsync((response) -> ((KuzzleMap) response.result).getNumber("count").intValue()); + } + + /** + * Sends a real-time message to Kuzzle. The message will be dispatched to + * all clients with subscriptions matching the index, the collection and + * the message content. + * + * @param index + * @param collection + * @param message + * @return + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture publish(final String index, final String collection, final ConcurrentHashMap message) throws NotConnectedException, InternalException { + return kuzzle + .query(new KuzzleMap() + .put("controller", "realtime") + .put("action", "publish") + .put("index", index) + .put("collection", collection) + .put("body", new KuzzleMap().put("message", message))) + .thenApplyAsync((response) -> null); + } + + public void renewSubscriptions() { + for (Map.Entry sub : subscriptionsCache.entrySet()) { + subscriptionsCache.get(sub.getKey()).clear(); + ((ArrayList) sub.getValue()).forEach(subscription -> + { + try { + subscribe(subscription); + } catch (NotConnectedException e) { + e.printStackTrace(); + } catch (InternalException e) { + e.printStackTrace(); + } + }); + } + } + + /** + * Subscribe to a collection. + * + * @param index + * @param collection + * @param filters + * @param handler + * @param options + * @return + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture subscribe(final String index, final String collection, final ConcurrentHashMap filters, final NotificationHandler handler, final SubscribeOptions options) throws NotConnectedException, InternalException { + ConcurrentHashMap queryOptions = new ConcurrentHashMap<>(); + final SubscribeOptions opts = (options == null ? new SubscribeOptions() : new SubscribeOptions(options)); + + synchronized (RealtimeController.class) { + if (opts != null) { + queryOptions = opts.toHashMap(); + } + } + + KuzzleMap query = new KuzzleMap(queryOptions) + .put("controller", "realtime") + .put("action", "subscribe") + .put("index", index) + .put("collection", collection) + .put("body", filters); + + return kuzzle + .query(query) + .thenApplyAsync( + (response) -> { + String channel = ((ConcurrentHashMap) response.result).get("channel").toString(); + Subscription subscription = new Subscription( + index, + collection, + filters, + handler, + opts + ); + + if (currentSubscriptions.get(channel) == null) { + ArrayList item = new ArrayList<>(); + item.add(subscription); + currentSubscriptions.put(channel, item); + subscriptionsCache.put(channel, item); + } else { + currentSubscriptions.get(channel).add(subscription); + subscriptionsCache.get(channel).add(subscription); + } + + return ((ConcurrentHashMap) response.result).get("roomId").toString(); + }); + } + + private CompletableFuture subscribe(final Subscription subscribe) throws NotConnectedException, InternalException { + return subscribe( + subscribe.index, + subscribe.collection, + subscribe.filter, + subscribe.handler, + subscribe.options + ); + } + + public CompletableFuture subscribe(final String index, final String collection, final ConcurrentHashMap filters, final NotificationHandler handler) throws NotConnectedException, InternalException { + return this.subscribe(index, collection, filters, handler, null); + } + + /** + * Removes a subscription + * + * @param roomId + * @return + * @throws NotConnectedException + * @throws InternalException + */ + public CompletableFuture unsubscribe(final String roomId) throws NotConnectedException, InternalException { + return kuzzle + .query(new KuzzleMap() + .put("controller", "realtime") + .put("action", "unsubscribe") + .put("body", new KuzzleMap().put("roomId", roomId))) + .thenApplyAsync((response) -> { + ArrayList subs = currentSubscriptions.get(roomId); + if (subs != null) { + currentSubscriptions.get(roomId).clear(); + } + subs = subscriptionsCache.get(roomId); + if (subs != null) { + subscriptionsCache.get(roomId).clear(); + } + return null; + }); + } +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Json/ConcurrentHashMapTypeAdapter.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Json/ConcurrentHashMapTypeAdapter.java new file mode 100644 index 00000000..f7c9776d --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Json/ConcurrentHashMapTypeAdapter.java @@ -0,0 +1,155 @@ +package io.kuzzle.sdk.CoreClasses.Json; + +import com.google.gson.JsonSyntaxException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.LazilyParsedNumber; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Maps.Serializable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class ConcurrentHashMapTypeAdapter + extends TypeAdapter> { + + @Override + public void write(JsonWriter out, ConcurrentHashMap map) + throws IOException { + if (map == null) { + out.nullValue(); + } else { + out.beginObject(); + Iterator> iterator = map.entrySet().iterator(); + + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + out.name(String.valueOf(entry.getKey())); + writeObject(out, entry.getValue()); + } + + out.endObject(); + } + } + + @Override + public ConcurrentHashMap read(JsonReader in) + throws IOException { + JsonToken peek = in.peek(); + if (peek == JsonToken.NULL) { + in.nextNull(); + return null; + } else if (peek == JsonToken.BEGIN_OBJECT) { + KuzzleMap map = new KuzzleMap(); + Object key; + Object value; + + in.beginObject(); + + while (in.hasNext()) { + key = in.nextName(); + value = readObject(in); + if (!map.containsKey(key)) { + map.put((String) key, value); + } else { + throw new JsonSyntaxException("duplicate key: " + key); + } + } + + in.endObject(); + + return map; + } + return null; + } + + private void writeObject(JsonWriter out, Object value) throws IOException { + if (value instanceof Number) { + out.value((Number) value); + } else if (value instanceof Boolean) { + out.value((Boolean) value); + } else if (value instanceof String) { + out.value((String) value); + } else if (value instanceof ArrayList) { + out.beginArray(); + Iterator iterator = ((ArrayList) value).iterator(); + + while (iterator.hasNext()) { + writeObject(out, iterator.next()); + } + + out.endArray(); + } else if (value instanceof ConcurrentHashMap) { + out.beginObject(); + Iterator> iterator = ((ConcurrentHashMap) value) + .entrySet() + .iterator(); + + while (iterator.hasNext()) { + Map.Entry e = iterator.next(); + out.name(e.getKey()); + writeObject(out, e.getValue()); + } + + out.endObject(); + } else if (value instanceof Serializable) { + try { + writeObject(out, ((Serializable) value).toMap()); + } catch (Exception e) { + throw new IOException(e); + } + } else if (value == null) { + out.nullValue(); + } + } + + private Object readObject(JsonReader in) throws IOException { + switch (in.peek()) { + case NUMBER: + String number = in.nextString(); + return new LazilyParsedNumber(number); + case BOOLEAN: + return in.nextBoolean(); + case STRING: + return in.nextString(); + case NULL: + in.nextNull(); + return null; + case BEGIN_ARRAY: + ArrayList array = new ArrayList<>(); + in.beginArray(); + + while (in.hasNext()) { + array.add(readObject(in)); + } + + in.endArray(); + return array; + case BEGIN_OBJECT: + KuzzleMap map = new KuzzleMap(); + in.beginObject(); + + while (in.hasNext()) { + String key = in.nextName(); + Object object = readObject(in); + if (object != null) { + map.put(key, object); + } + } + + in.endObject(); + return map; + case END_DOCUMENT: + case NAME: + case END_OBJECT: + case END_ARRAY: + default: + throw new IllegalArgumentException(); + } + } +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Json/JsonSerializer.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Json/JsonSerializer.java new file mode 100644 index 00000000..8abfaf36 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Json/JsonSerializer.java @@ -0,0 +1,28 @@ +package io.kuzzle.sdk.CoreClasses.Json; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.concurrent.ConcurrentHashMap; + +public class JsonSerializer { + private static Gson gson; + + static { + gson = new GsonBuilder() + .disableHtmlEscaping() + .disableInnerClassSerialization() + .serializeNulls() + .registerTypeAdapter(ConcurrentHashMap.class, + new ConcurrentHashMapTypeAdapter()) + .create(); + } + + public static ConcurrentHashMap deserialize(String rawJson) { + return gson.fromJson(rawJson, ConcurrentHashMap.class); + } + + public static String serialize(ConcurrentHashMap map) { + return gson.toJson(map, ConcurrentHashMap.class); + } +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/KuzzleMap.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/KuzzleMap.java new file mode 100644 index 00000000..96dae224 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/KuzzleMap.java @@ -0,0 +1,278 @@ +package io.kuzzle.sdk.CoreClasses.Maps; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +/** + * CustomMap is a Class that extends ConcurrentHashMap to be ThreadSafe and that + * has the purpose of giving a wrapper on top of ConcurrentHashMap to easily + * manipulate them. + */ +public class KuzzleMap extends ConcurrentHashMap { + + /** + * serialVersionUID + */ + private static final long serialVersionUID = -3027862451021177820L; + + /** + * Convert à ConcurrentHashMap to a CustomMap + * + * @param map + * ConcurrentHashMap representing JSON. + * @return a CustomMap instance + */ + public static KuzzleMap from(ConcurrentHashMap map) { + if (map == null) { + return null; + } + if (map instanceof KuzzleMap) { + return (KuzzleMap) map; + } + return new KuzzleMap(map); + } + + /** + * Create a new instance of CustomMap + */ + public KuzzleMap() { + super(); + } + + /** + * Create a new instance of CustomMap from a ConcurrentHashMap. + * + * @param map + * ConcurrentHashMap representing JSON. + */ + public KuzzleMap(ConcurrentHashMap map) { + super(); + Iterator> it = map.entrySet().iterator(); + + while (it.hasNext()) { + Entry entry = it.next(); + this.put(entry.getKey(), entry.getValue()); + } + } + + @Override + public KuzzleMap put(String s, Object o) { + if (o != null) { + super.put(s, o); + } else { + super.put(s, new Null()); + } + + return this; + } + + @Override + public Object get(Object key) { + Object value = super.get(key); + if (value instanceof Null) { + return null; + } + return value; + } + + @Override + public Set> entrySet() { + Set> entrySet = super.entrySet(); + return entrySet.parallelStream().map((Entry entry) -> { + if (entry.getValue() instanceof Null) { + return new KuzzleMapEntry(entry.getKey(), entry.getValue(), this); + } + return entry; + }).collect(Collectors.toSet()); + } + + /** + * Check whether the key value is null or not. + * + * @param key + * a String representing the key. + * @return true if the value is null. + */ + public boolean isNull(String key) { + return super.get(key) instanceof Null; + } + + /** + * Check whether the key value is a String or not. + * + * @param key + * a String representing the key. + * @return true if the key is a String. + */ + public boolean isString(String key) { + return super.get(key) instanceof String; + } + + /** + * Check whether the key value is a Boolean or not. + * + * @param key + * a String representing the key. + * @return true if the key is a Boolean. + */ + public boolean isBoolean(String key) { + return super.get(key) instanceof Boolean; + } + + /** + * Check whether the key value is a Number or not. + * + * @param key + * a String representing the key. + * @return true if the key is a Number. + */ + public boolean isNumber(String key) { + return super.get(key) instanceof Number; + } + + /** + * Check whether the key value is an ArrayList or not. + * + * @param key + * a String representing the key. + * @return true if the key is an ArrayList. + */ + public boolean isArrayList(String key) { + return super.get(key) instanceof ArrayList; + } + + /** + * Check whether the key value is a ConcurrentHashMap or not. + * + * @param key + * a String representing the key. + * @return true if the key is a ConcurrentHashMap. + */ + public boolean isMap(String key) { + return super.get(key) instanceof ConcurrentHashMap; + } + + /** + * Return the specified key value or null if the value is not a String. + * + * @param key + * a String representing the key. + * @return The String at the key or null + */ + public String getString(String key) { + return isString(key) ? (String) super.get(key) : null; + } + + /** + * Return the specified key value or null if the value is not a Boolean. + * + * @param key + * a String representing the key. + * @return The Boolean at the key or null + */ + public Boolean getBoolean(String key) { + return isBoolean(key) ? (Boolean) super.get(key) : null; + } + + /** + * Return the specified key value or null if the value is not a Number. + * + * @param key + * a String representing the key. + * @return The Number at the key or null + */ + public Number getNumber(String key) { + return isNumber(key) ? (Number) super.get(key) : null; + } + + /** + * Return the specified key value or null if the value is not an ArrayList. + * + * @param key + * a String representing the key. + * @return The ArrayList at the key or null + */ + public ArrayList getArrayList(String key) { + return isArrayList(key) ? (ArrayList) super.get(key) : null; + } + + /** + * Return the specified key value or null if the value is not a + * ConcurrentHashMap. + * + * @param key + * a String representing the key. + * @return The ConcurrentHashMap at the key or null + */ + public KuzzleMap getMap(String key) { + return isMap(key) + ? KuzzleMap.from((ConcurrentHashMap) super.get(key)) + : null; + } + + /** + * Return the specified key value or the def value if the value is nul or not + * a String. + * + * @param key + * a String representing the key. + * @return The String at the key or def value + */ + public String optString(String key, String def) { + return isString(key) ? (String) super.get(key) : def; + } + + /** + * Return the specified key value or the def value if the value is nul or not + * a Boolean. + * + * @param key + * a String representing the key. + * @return The Boolean at the key or def value + */ + public Boolean optBoolean(String key, Boolean def) { + return isBoolean(key) ? (Boolean) super.get(key) : def; + } + + /** + * Return the specified key value or the def value if the value is nul or not + * a Number. + * + * @param key + * a String representing the key. + * @return The Number at the key or def value + */ + public Number optNumber(String key, Number def) { + return isNumber(key) ? (Number) super.get(key) : def; + } + + /** + * Return the specified key value or the def value if the value is nul or not + * an ArrayList. + * + * @param key + * a String representing the key. + * @return The ArrayList at the key or def value + */ + public ArrayList optArrayList(String key, ArrayList def) { + return isArrayList(key) ? (ArrayList) super.get(key) : def; + } + + /** + * Return the specified key value or the def value if the value is nul or not + * a ConcurrentHashMap. + * + * @param key + * a String representing the key. + * @return The ConcurrentHashMap at the key or def value + */ + public KuzzleMap optMap(String key, ConcurrentHashMap def) { + return isMap(key) + ? KuzzleMap.from((ConcurrentHashMap) super.get(key)) + : KuzzleMap.from(def); + } +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/KuzzleMapEntry.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/KuzzleMapEntry.java new file mode 100644 index 00000000..65b8548b --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/KuzzleMapEntry.java @@ -0,0 +1,64 @@ +package io.kuzzle.sdk.CoreClasses.Maps; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class KuzzleMapEntry implements Map.Entry { + final String key; + Object value; + final ConcurrentHashMap map; + + public KuzzleMapEntry(String key, Object value, ConcurrentHashMap map) { + this.key = key; + this.value = value; + this.map = map; + } + + public String getKey() { + return this.key; + } + + public Object getValue() { + if (this.value instanceof Null) { + return null; + } + return this.value; + } + + public int hashCode() { + return this.key.hashCode() ^ this.value.hashCode(); + } + + public String toString() { + return this.key + "=" + this.value; + } + + public boolean equals(Object object) { + Object key; + Object value; + Map.Entry entry; + + if (!(object instanceof Map.Entry)) { + return false; + } + + entry = (Map.Entry) object; + key = entry.getKey(); + value = entry.getValue(); + return key != null && (value == this.value || (value != null && value.equals(this.value))); + } + + public Object setValue(Object value) { + if (value == null) { + Object oldValue = this.value; + this.value = new Null(); + this.map.put(this.key, this.value); + return oldValue; + } else { + Object oldValue = this.value; + this.value = value; + this.map.put(this.key, value); + return oldValue; + } + } +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/Null.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/Null.java new file mode 100644 index 00000000..b9d0350d --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/Null.java @@ -0,0 +1,13 @@ +package io.kuzzle.sdk.CoreClasses.Maps; + +public class Null { + final int hashCode = 572487463; + + public int hashCode() { + return hashCode; + } + + public String toString() { + return "null"; + } +} \ No newline at end of file diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/Serializable.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/Serializable.java new file mode 100644 index 00000000..ebc0c7af --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Maps/Serializable.java @@ -0,0 +1,9 @@ +package io.kuzzle.sdk.CoreClasses.Maps; + +import java.util.concurrent.ConcurrentHashMap; + +public interface Serializable { + void fromMap(ConcurrentHashMap map) throws Exception; + + ConcurrentHashMap toMap() throws Exception; +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Responses/ErrorResponse.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Responses/ErrorResponse.java new file mode 100644 index 00000000..ae989dce --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Responses/ErrorResponse.java @@ -0,0 +1,57 @@ +package io.kuzzle.sdk.CoreClasses.Responses; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Maps.Serializable; + +import java.util.concurrent.ConcurrentHashMap; + +public class ErrorResponse implements Serializable { + + public ErrorResponse() { + + } + + /** + * Response status, following HTTP status codes. + */ + public int status; + + /** + * Error message + */ + public String message; + + /** + * Error ID + */ + public String id; + + /** + * Error stack + */ + public String stack; + + @Override + public void fromMap(ConcurrentHashMap map) { + if (map == null) + return; + + KuzzleMap kuzzleMap = KuzzleMap.from(map); + + status = kuzzleMap.optNumber("status", 0).intValue(); + message = kuzzleMap.getString("message"); + stack = kuzzleMap.getString("stack"); + id = kuzzleMap.getString("id"); + } + + @Override + public ConcurrentHashMap toMap() { + ConcurrentHashMap map = new KuzzleMap(); + + map.put("status", status); + map.put("message", message); + map.put("stack", stack); + map.put("id", id); + return map; + } +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Responses/Response.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Responses/Response.java new file mode 100644 index 00000000..882d1e01 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Responses/Response.java @@ -0,0 +1,140 @@ +package io.kuzzle.sdk.CoreClasses.Responses; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Maps.Serializable; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.KuzzleExceptionCode; + +import java.util.concurrent.ConcurrentHashMap; + +public class Response implements Serializable { + + public String room; + + /** + * Response payload (depends on the executed API action) + */ + public Object result; + + /** + * Error object (null if the request finished successfully) + */ + public ErrorResponse error; + + /** + * Request unique identifier. + */ + public String requestId; + + /** + * Response status, following HTTP status codes + */ + public int status; + + /** + * Executed Kuzzle API controller. + */ + public String controller; + + /** + * Executed Kuzzle API controller's action. + */ + public String action; + + /** + * Impacted data index. + */ + public String index; + + /** + * Impacted data collection. + */ + public String collection; + + /** + * Volatile data. + */ + public ConcurrentHashMap Volatile; + + // The following properties are specific to real-time notifications + + /** + * Network protocol at the origin of the real-time notification. + */ + public String protocol; + + /** + * Document scope ("in" or "out") + */ + public String scope; + + /** + * Document state + */ + public String state; + + /** + * Notification timestamp (UTC) + */ + public Long timestamp; + + /** + * Notification type + */ + public String type; + + @Override + public void fromMap(ConcurrentHashMap map) + throws InternalException { + if (map == null) + return; + + KuzzleMap kuzzleMap = KuzzleMap.from(map); + + room = kuzzleMap.getString("room"); + result = kuzzleMap.get("result"); + error = null; + if (kuzzleMap.isMap("error")) { + error = new ErrorResponse(); + error.fromMap(kuzzleMap.getMap("error")); + } + requestId = kuzzleMap.getString("requestId"); + if (requestId == null) { + throw new InternalException(KuzzleExceptionCode.MISSING_REQUESTID); + } + status = kuzzleMap.optNumber("status", 0).intValue(); + controller = kuzzleMap.getString("controller"); + action = kuzzleMap.getString("action"); + index = kuzzleMap.getString("index"); + collection = kuzzleMap.getString("collection"); + Volatile = kuzzleMap.optMap("volatile", new ConcurrentHashMap<>()); + protocol = kuzzleMap.getString("protocol"); + scope = kuzzleMap.getString("scope"); + state = kuzzleMap.getString("state"); + timestamp = (kuzzleMap.getNumber("timestamp") == null ? null : kuzzleMap.getNumber("timestamp").longValue()); + type = kuzzleMap.getString("type"); + } + + @Override + public ConcurrentHashMap toMap() { + ConcurrentHashMap map = new KuzzleMap(); + + map.put("room", room); + map.put("result", result); + map.put("error", error); + map.put("requestId", requestId); + map.put("status", status); + map.put("controller", controller); + map.put("action", action); + map.put("index", index); + map.put("collection", collection); + map.put("volatile", Volatile); + map.put("protocol", protocol); + map.put("scope", scope); + map.put("status", status); + map.put("timestamp", timestamp); + map.put("type", type); + + return map; + } +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/SearchResult.java b/src/main/java/io/kuzzle/sdk/CoreClasses/SearchResult.java new file mode 100644 index 00000000..931a6646 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/SearchResult.java @@ -0,0 +1,133 @@ +package io.kuzzle.sdk.CoreClasses; + +import com.google.gson.internal.LazilyParsedNumber; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Options.SearchOptions; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.jar.JarOutputStream; + +public class SearchResult { + + private SearchOptions options; + private ConcurrentHashMap request; + private String scrollAction = "scroll"; + private Kuzzle kuzzle; + + public ConcurrentHashMap aggregations; + public ArrayList> hits; + public Integer total; + public Integer fetched; + public String scrollId; + + public SearchResult( + Kuzzle kuzzle, + ConcurrentHashMap request, + SearchOptions options, + Response response) { + + ConcurrentHashMap _response = response.toMap(); + + this.kuzzle = kuzzle; + this.options = options; + this.request = request; + + this.aggregations = (ConcurrentHashMap) ((ConcurrentHashMap) _response.get("result")).get("aggregations"); + this.hits = (ArrayList>) ((ConcurrentHashMap) _response.get("result")).get("hits"); + this.total = ((LazilyParsedNumber) ((ConcurrentHashMap) _response.get("result")).get("total")).intValue(); + this.fetched = hits.size(); + this.scrollId = (String) ((ConcurrentHashMap) _response.get("result")).get("scrollId"); + } + + public SearchResult( + Kuzzle kuzzle, + ConcurrentHashMap request, + SearchOptions options, + Response response, + Integer previouslyFetched) { + + ConcurrentHashMap _response = response.toMap(); + + this.kuzzle = kuzzle; + this.options = options; + this.request = request; + + this.aggregations = (ConcurrentHashMap) ((ConcurrentHashMap) _response.get("result")).get("aggregations"); + this.hits = (ArrayList>) ((ConcurrentHashMap) _response.get("result")).get("hits"); + this.total = ((LazilyParsedNumber) ((ConcurrentHashMap) _response.get("result")).get("total")).intValue(); + this.fetched = hits.size() + previouslyFetched; + this.scrollId = (String) ((ConcurrentHashMap) _response.get("result")).get("scrollId"); + } + + private ConcurrentHashMap getScrollRequest() { + final ConcurrentHashMap obj = new ConcurrentHashMap<>(); + + obj.put("controller", this.request.get("controller")); + obj.put("action", this.scrollAction); + obj.put("scrollId", this.scrollId); + return obj; + } + + private ConcurrentHashMap getSearchAfterRequest() { + ConcurrentHashMap nextRequest = this.request; + ConcurrentHashMap lastItem = this.hits.get(this.hits.size()); + ArrayList searchAfter = new ArrayList<>(); + ArrayList sort = (ArrayList) ((ConcurrentHashMap) this.request.get("body")).get("sort"); + + ((ConcurrentHashMap) this.request.get("body")).put("search_after", searchAfter); + + for (Object value : sort) { + String key; + + if (value instanceof String) { + key = value.toString(); + } else { + key = ((ConcurrentHashMap) value).get("First").toString(); + } + + if (key.equals("_uid")) { + searchAfter.add(this.request.get("collection").toString() + "#" + lastItem.get("_id").toString()); + } else { + ConcurrentHashMap _source = (ConcurrentHashMap) lastItem.get("_source"); + searchAfter.add(_source.get(key)); + } + } + return nextRequest; + } + + public CompletableFuture next() throws NotConnectedException, InternalException, ExecutionException, InterruptedException { + + if (this.fetched >= this.total) return CompletableFuture.completedFuture(null); + + ConcurrentHashMap nextRequest = new ConcurrentHashMap<>(); + if (this.scrollId != null) { + nextRequest = this.getScrollRequest(); + } else if (this.options.getSize() != null + && ((ConcurrentHashMap) this.request.get("body")).get("sort") != null) { + nextRequest = this.getSearchAfterRequest(); + } else if (this.options.getSize() != null) { + if (this.options.getFrom() != null && this.options.getFrom() > this.total) { + return CompletableFuture.completedFuture(null); + } + + this.options.setFrom(this.fetched); + nextRequest = this.request; + } + + if (nextRequest == null) { + return CompletableFuture.completedFuture(null); + } + + final ConcurrentHashMap request = nextRequest; + return this.kuzzle.query(nextRequest) + .thenApplyAsync( + (response) -> new SearchResult(this.kuzzle, request, this.options, response, this.fetched)); + } +} diff --git a/src/main/java/io/kuzzle/sdk/CoreClasses/Task.java b/src/main/java/io/kuzzle/sdk/CoreClasses/Task.java new file mode 100644 index 00000000..4039187b --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/CoreClasses/Task.java @@ -0,0 +1,75 @@ +package io.kuzzle.sdk.CoreClasses; + +import java.util.concurrent.CompletableFuture; + +/** + * @param The object type that the task return. + */ +public class Task { + /** + * A completable future. + */ + protected CompletableFuture future = new CompletableFuture<>(); + + /** + * @return The associated CompletableFuture. + */ + public CompletableFuture getFuture() { + return future; + } + + /** + * Set the exception of the CompletableFuture. + * + * @param exception + */ + public void setException(Exception exception) { + future.completeExceptionally(exception); + } + + /** + * @return true if future is cancelled. + */ + public boolean isCancelled() { + return future.isCancelled(); + } + + /** + * @return true if the future is done. + */ + public boolean isDone() { + return future.isDone(); + } + + /** + * @return true if the future has been completed exceptionally. + */ + public boolean isCompletedExceptionally() { + return future.isCompletedExceptionally(); + } + + /** + * Set if the future is cancelled. + * + * @param state + */ + public void setCancelled(boolean state) { + future.cancel(state); + } + + /** + * Unlock the future. + */ + public void trigger() { + future.complete(null); + } + + /** + * Unlock the future and set the object. + * + * @param object + */ + public void trigger(T object) { + future.complete(object); + } +} diff --git a/src/main/java/io/kuzzle/sdk/Events/Event.java b/src/main/java/io/kuzzle/sdk/Events/Event.java new file mode 100644 index 00000000..87a89785 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Events/Event.java @@ -0,0 +1,18 @@ +package io.kuzzle.sdk.Events; + +/** + * The enum Event type. + */ +public enum Event { + disconnected, + reconnected, + connected, + error, + tokenExpired, + loginAttempt, + offlineQueuePush, + offlineQueuePop, + unhandledResponse, + networkResponseReceived, + networkStateChange +} diff --git a/src/main/java/io/kuzzle/sdk/Events/EventListener.java b/src/main/java/io/kuzzle/sdk/Events/EventListener.java new file mode 100644 index 00000000..860b3a79 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Events/EventListener.java @@ -0,0 +1,5 @@ +package io.kuzzle.sdk.Events; + +public interface EventListener { + void trigger(Object... args); +} diff --git a/src/main/java/io/kuzzle/sdk/Events/EventManager.java b/src/main/java/io/kuzzle/sdk/Events/EventManager.java new file mode 100644 index 00000000..305129a3 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Events/EventManager.java @@ -0,0 +1,62 @@ +package io.kuzzle.sdk.Events; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +public class EventManager { + /** + * List of listener. + */ + protected ConcurrentHashMap> listeners = new ConcurrentHashMap<>(); + + /** + * Register a listener. + * + * @param event + * @param listener + * @return If successfully registered. + */ + public synchronized boolean register(final Event event, + final EventListener listener) { + listeners.computeIfAbsent(event, l -> new ArrayList<>()); + + List eventListener = listeners.get(event); + if (eventListener != null) { + return listeners.get(event).add(listener); + } + return false; + } + + /** + * Unregister a listener. + * + * @param event + * @param listener + * @return If successfully unregistered. + */ + public synchronized boolean unregister(final Event event, + final EventListener listener) { + if (!listeners.containsKey(event)) { + return false; + } + return listeners.get(event).remove(listener); + } + + /** + * Triggers every listener of the same event type. + * + * @param args + * An array of Object. + */ + public void trigger(final Event event, Object... args) { + List eventListener = listeners.get(event); + if (eventListener != null) { + for (final EventListener listener : eventListener) { + if (listener != null) { + listener.trigger(args); + } + } + } + } +} diff --git a/src/main/java/io/kuzzle/sdk/Exceptions/ApiErrorException.java b/src/main/java/io/kuzzle/sdk/Exceptions/ApiErrorException.java new file mode 100644 index 00000000..8bcf73a1 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Exceptions/ApiErrorException.java @@ -0,0 +1,44 @@ +package io.kuzzle.sdk.Exceptions; + +import io.kuzzle.sdk.CoreClasses.Responses.Response; + +/** + * Passed to async tasks when an API request returns an error. + */ +public class ApiErrorException extends KuzzleException { + /** + * + */ + private static final long serialVersionUID = 666379398727075901L; + + /** + * Kuzzle API stack trace + */ + protected String stack; + + /** + * Kuzzle API error unique identifier + */ + protected String id; + + /** + * Initializes a new instance of the ApiErrorException + * + * @param response Kuzzle API Response. + */ + public ApiErrorException(Response response) { + super(response.error != null ? response.error.message : null, response.status); + if (response.error != null) { + this.stack = response.error.stack; + this.id = response.error.id; + } + } + + public String getStack() { + return this.stack; + } + + public String getId() { + return this.id; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Exceptions/ConnectionLostException.java b/src/main/java/io/kuzzle/sdk/Exceptions/ConnectionLostException.java new file mode 100644 index 00000000..89804fa3 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Exceptions/ConnectionLostException.java @@ -0,0 +1,20 @@ +package io.kuzzle.sdk.Exceptions; + +/** + * Thrown to close ongoing API tasks, when the connection has been lost while + * waiting for a result. + */ +public class ConnectionLostException extends KuzzleException { + /** + * + */ + private static final long serialVersionUID = 1046624032334173580L; + + /** + * Initializes a new instance of the ConnectionLostException. + */ + public ConnectionLostException() { + super(KuzzleExceptionCode.CONNECTION_LOST); + } + +} diff --git a/src/main/java/io/kuzzle/sdk/Exceptions/InternalException.java b/src/main/java/io/kuzzle/sdk/Exceptions/InternalException.java new file mode 100644 index 00000000..a5296651 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Exceptions/InternalException.java @@ -0,0 +1,24 @@ +package io.kuzzle.sdk.Exceptions; + +/** + * Passed to async tasks when an API request returns an error. + */ +public class InternalException extends KuzzleException { + + /** + * + */ + private static final long serialVersionUID = -7004783427215842992L; + + /** + * Initializes a new instance of the InternalException + */ + public InternalException(String message, KuzzleExceptionCode status) { + super(message, status); + } + + public InternalException(KuzzleExceptionCode status) { + super(status); + } + +} diff --git a/src/main/java/io/kuzzle/sdk/Exceptions/KuzzleException.java b/src/main/java/io/kuzzle/sdk/Exceptions/KuzzleException.java new file mode 100644 index 00000000..8c036c40 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Exceptions/KuzzleException.java @@ -0,0 +1,46 @@ +package io.kuzzle.sdk.Exceptions; + +/** + * Root of all Kuzzle exceptions. + */ +public class KuzzleException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 4446507573441857492L; + /** + * Kuzzle API error code. + */ + protected int status; + + /** + * Initializes a new instance of the KuzzleException. + * + * @param message + * Message. + * @param status + * Status. + */ + protected KuzzleException(String message, int status) { + super(message); + this.status = status; + } + + protected KuzzleException(String message, KuzzleExceptionCode status) { + super(message); + this.status = status.getCode(); + } + + protected KuzzleException(KuzzleExceptionCode status) { + super(status.getMessage()); + this.status = status.getCode(); + } + + /** + * @return The status code of the exception. + */ + public int getStatus() { + return status; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Exceptions/KuzzleExceptionCode.java b/src/main/java/io/kuzzle/sdk/Exceptions/KuzzleExceptionCode.java new file mode 100644 index 00000000..a4edf6f1 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Exceptions/KuzzleExceptionCode.java @@ -0,0 +1,32 @@ +package io.kuzzle.sdk.Exceptions; + +public enum KuzzleExceptionCode { + MISSING_REQUESTID(0, "Missing field requestId"), + MISSING_QUERY(400, "You must provide a query"), + NOT_CONNECTED(500, "Not connected."), + CONNECTION_LOST(500, "Connection lost"), + WRONG_VOLATILE_TYPE( + 400, + "Volatile data must be a ConcurrentHashMap"); + + private final int code; + private final String message; + + KuzzleExceptionCode(final int code) { + this.code = code; + this.message = null; + } + + KuzzleExceptionCode(final int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return this.code; + } + + public String getMessage() { + return this.message; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Exceptions/NotConnectedException.java b/src/main/java/io/kuzzle/sdk/Exceptions/NotConnectedException.java new file mode 100644 index 00000000..1d85a3e7 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Exceptions/NotConnectedException.java @@ -0,0 +1,19 @@ +package io.kuzzle.sdk.Exceptions; + +/** + * Thrown when attempting to interact with the network while not connected. + */ +public class NotConnectedException extends KuzzleException { + + /** + * + */ + private static final long serialVersionUID = 1961824705891656436L; + + /** + * Initializes a new instance of the NotConnectedException. + */ + public NotConnectedException() { + super(KuzzleExceptionCode.NOT_CONNECTED); + } +} diff --git a/src/main/java/io/kuzzle/sdk/Handlers/NotificationHandler.java b/src/main/java/io/kuzzle/sdk/Handlers/NotificationHandler.java new file mode 100644 index 00000000..0029030c --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Handlers/NotificationHandler.java @@ -0,0 +1,7 @@ +package io.kuzzle.sdk.Handlers; + +import io.kuzzle.sdk.CoreClasses.Responses.Response; + +public interface NotificationHandler { + void run(Response notification); +} diff --git a/src/main/java/io/kuzzle/sdk/Helpers/Default.java b/src/main/java/io/kuzzle/sdk/Helpers/Default.java new file mode 100644 index 00000000..fc582719 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Helpers/Default.java @@ -0,0 +1,16 @@ +package io.kuzzle.sdk.Helpers; + +public class Default { + + /** + * Return the object or its default value in the case of the object is null. + * + * @param obj An object. + * @param defaultValue A default value in case your object is null. + * @param Object class. + * @return The object or the specified default value in case the object is null. + */ + public static T defaultValue(T obj, T defaultValue) { + return obj != null ? obj : defaultValue; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Kuzzle.java b/src/main/java/io/kuzzle/sdk/Kuzzle.java new file mode 100644 index 00000000..84f5a825 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Kuzzle.java @@ -0,0 +1,306 @@ +package io.kuzzle.sdk; + +import io.kuzzle.sdk.API.Controllers.AuthController; +import io.kuzzle.sdk.API.Controllers.CollectionController; +import io.kuzzle.sdk.API.Controllers.DocumentController; +import io.kuzzle.sdk.API.Controllers.IndexController; +import io.kuzzle.sdk.API.Controllers.RealtimeController; +import io.kuzzle.sdk.CoreClasses.Json.JsonSerializer; +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Task; +import io.kuzzle.sdk.Exceptions.*; +import io.kuzzle.sdk.Options.KuzzleOptions; +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.ProtocolState; +import io.kuzzle.sdk.CoreClasses.Responses.*; +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Events.EventManager; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +public class Kuzzle extends EventManager { + protected final AbstractProtocol networkProtocol; + + public final String version; + public final String instanceId; + public final String sdkName; + + /** + * Authentication token + */ + protected AtomicReference authenticationToken; + + /** + * The maximum amount of elements that the queue can contains. If set to -1, + * the size is unlimited. + */ + protected AtomicInteger maxQueueSize; + + /** + * The minimum duration of a Token before being automatically refreshed. If + * set to -1 the SDK does not refresh the token automatically. + */ + protected AtomicInteger minTokenDuration; + + /** + * The minimum duration of a Token after refresh. If set to -1 the SDK does + * not refresh the token automatically. + */ + protected AtomicInteger refreshedTokenDuration; + + /** + * The maximum delay between two requests to be replayed + */ + protected AtomicInteger maxRequestDelay; + + protected ConcurrentHashMap> requests = new ConcurrentHashMap<>(); + + private RealtimeController realtimeController; + + private boolean autoResubscribe; + + /** + * Initialize a new instance of Kuzzle + * + * @param networkProtocol The network protocol + * @throws IllegalArgumentException + */ + public Kuzzle(final AbstractProtocol networkProtocol) + throws IllegalArgumentException { + this(networkProtocol, new KuzzleOptions()); + } + + /** + * @return The AuthController + */ + public AuthController getAuthController() { + return new AuthController(this); + } + + /** + * @return The CollectionController + */ + public CollectionController getCollectionController() { + return new CollectionController(this); + } + + /** + * @return The DocumentController + */ + public DocumentController getDocumentController() { + return new DocumentController(this); + } + + /** + * @return The IndexController + */ + public IndexController getIndexController() { + return new IndexController(this); + } + + /** + * @return RealtimeController + */ + public RealtimeController getRealtimeController() { + if (this.realtimeController == null) { + synchronized (Kuzzle.class) { + if (this.realtimeController == null) { + this.realtimeController = new RealtimeController(this); + } + } + } + return this.realtimeController; + } + + /** + * Initialize a new instance of Kuzzle + * + * @param networkProtocol The network protocol + * @param options Kuzzle options + * @throws IllegalArgumentException + */ + public Kuzzle(final AbstractProtocol networkProtocol, + final KuzzleOptions options) throws IllegalArgumentException { + if (networkProtocol == null) { + throw new IllegalArgumentException("networkProtocol can't be null"); + } + + final KuzzleOptions kOptions = options != null ? options + : new KuzzleOptions(); + + this.networkProtocol = networkProtocol; + this.networkProtocol + .register(Event.networkResponseReceived, this::onResponseReceived); + this.networkProtocol + .register(Event.networkStateChange, this::onStateChanged); + + this.maxQueueSize = new AtomicInteger(kOptions.getMaxQueueSize()); + this.minTokenDuration = new AtomicInteger(kOptions.getMinTokenDuration()); + this.refreshedTokenDuration = new AtomicInteger( + kOptions.getRefreshedTokenDuration()); + this.maxRequestDelay = new AtomicInteger(kOptions.getMaxRequestDelay()); + + this.autoResubscribe = kOptions.isAutoResubscribe(); + + this.version = "3"; + this.instanceId = UUID.randomUUID().toString(); + this.sdkName = "java@" + version; + } + + /** + * Establish a network connection + * + * @throws Exception + */ + public void connect() throws Exception { + networkProtocol.connect(); + } + + /** + * Disconnect this instance + */ + public void disconnect() { + networkProtocol.disconnect(); + } + + /** + * Handles the ResponseReceivedEvent from the network protocol + * + * @param payload Raw API Response + */ + protected void onResponseReceived(final Object... payload) { + final Response response = new Response(); + try { + response.fromMap(JsonSerializer.deserialize(payload[0].toString())); + } catch (final Exception e) { + e.printStackTrace(); + return; + } + + if (requests != null && (response.room == null || !requests.containsKey(response.room))) { + super.trigger(Event.unhandledResponse, response); + return; + } + + if (response.error == null) { + final Task task = requests.get(response.requestId); + + if (task != null) { + task.trigger(response); + } + + requests.remove(response.requestId); + return; + } + + if (response.error.id == null + || !response.error.id.equals("security.token.expired")) { + final Task task = requests.get(response.requestId); + if (task != null) { + task.setException(new ApiErrorException(response)); + } + return; + } + + super.trigger(Event.tokenExpired); + } + + protected void onStateChanged(final Object... args) { + // If not connected anymore: close tasks and clean up the requests buffer + if (args[0] == ProtocolState.CLOSE) { + for (final Task task : requests.values()) { + task.setException(new ConnectionLostException()); + } + requests.clear(); + } else if (args[0] == ProtocolState.OPEN && realtimeController != null && autoResubscribe) { + realtimeController.renewSubscriptions(); + } + } + + /** + * Sends an API request to Kuzzle and returns the corresponding API + * + * @param query Kuzzle API query + * @return A CompletableFuture + * @throws InternalException + * @throws NotConnectedException + */ + public CompletableFuture query( + final ConcurrentHashMap query) + throws InternalException, NotConnectedException { + if (query == null) { + throw new InternalException(KuzzleExceptionCode.MISSING_QUERY); + } + + + if (networkProtocol.getState() == ProtocolState.CLOSE) { + throw new NotConnectedException(); + } + final KuzzleMap queryMap = KuzzleMap.from(query); + + if (queryMap.containsKey("waitForRefresh")) { + if (queryMap.optBoolean("waitForRefresh", false).booleanValue()) { + queryMap.put("refresh", "wait_for"); + } + queryMap.remove("waitForRefresh"); + } + + if (authenticationToken != null) { + queryMap.put("jwt", authenticationToken.toString()); + } + + final String requestId = UUID.randomUUID().toString(); + + queryMap.put("requestId", requestId); + + if (!queryMap.containsKey("volatile") || queryMap.isNull("volatile")) { + queryMap.put("volatile", new KuzzleMap()); + } else if (!queryMap.isMap("volatile")) { + throw new InternalException(KuzzleExceptionCode.WRONG_VOLATILE_TYPE); + } + + queryMap.getMap("volatile").put("sdkInstanceId", instanceId); + + queryMap.getMap("volatile").put("sdkName", sdkName); + + final Task task = new Task<>(); + requests.put(requestId, task); + + if (networkProtocol.getState() == ProtocolState.OPEN) { + networkProtocol.send(queryMap); + } + + return task.getFuture(); + } + + /** + * @return The authentication token + */ + public String getAuthenticationToken() { + return authenticationToken.get(); + } + + /** + * Set the authentication token + * + * @param token Authentication token + */ + public void setAuthenticationToken(final String token) { + if (authenticationToken == null) { + authenticationToken = new AtomicReference<>(); + } + authenticationToken.set(token); + } + + public boolean isAutoResubscribe() { + return autoResubscribe; + } + + public void setAutoResubscribe(boolean autoResubscribe) { + this.autoResubscribe = autoResubscribe; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Options/CreateOptions.java b/src/main/java/io/kuzzle/sdk/Options/CreateOptions.java new file mode 100644 index 00000000..7e11f4da --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Options/CreateOptions.java @@ -0,0 +1,59 @@ +package io.kuzzle.sdk.Options; + +import java.util.concurrent.ConcurrentHashMap; + +public class CreateOptions { + + private String id; + private Integer retryOnConflict; + private Boolean waitForRefresh; + /** + * Constructor + */ + public CreateOptions() {} + + /** + * Copy constructor + * + * @param options + */ + public CreateOptions(CreateOptions options) { + this.id = options.getId(); + this.waitForRefresh = options.getWaitForRefresh(); + this.retryOnConflict = options.getRetryOnConflict(); + } + + public Integer getRetryOnConflict() { + return retryOnConflict; + } + + public Boolean getWaitForRefresh() { + return waitForRefresh; + } + + public String getId() { + return id; + } + + public void setWaitForRefresh(Boolean waitForRefresh) { + this.waitForRefresh = waitForRefresh; + } + + public void setId(String id) { + this.id = id; + } + + public void setRetryOnConflict(Integer retryOnConflict) { + this.retryOnConflict = retryOnConflict; + } + + public ConcurrentHashMap toHashMap() { + ConcurrentHashMap options = new ConcurrentHashMap<>(); + + options.put("_id", this.id); + options.put("waitForRefresh", this.waitForRefresh); + options.put("retryOnConflict", this.retryOnConflict); + + return options; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Options/KuzzleOptions.java b/src/main/java/io/kuzzle/sdk/Options/KuzzleOptions.java new file mode 100644 index 00000000..fed2d840 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Options/KuzzleOptions.java @@ -0,0 +1,162 @@ +package io.kuzzle.sdk.Options; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; + +import static io.kuzzle.sdk.Helpers.Default.defaultValue; + +public class KuzzleOptions { + + /** + * The maximum amount of elements that the queue can contains. If set to -1, + * the size is unlimited. + */ + private int maxQueueSize = -1; + + /** + * The minimum duration of a Token before being automatically refreshed. If + * set to -1 the SDK does not refresh the token automatically. + */ + private int minTokenDuration = 3_600_000; + + /** + * The minimum duration of a Token after refresh. If set to -1 the SDK does + * not refresh the token automatically. + */ + private int refreshedTokenDuration = 3_600_000; + + /** + * The maximum delay between two requests to be replayed. + */ + private int maxRequestDelay = 1000; + + private Predicate> queueFilter = ( + ConcurrentHashMap obj) -> true; + + private boolean autoResubscribe = true; + + /** + * Initialize a new KuzzleOptions instance. + */ + public KuzzleOptions() { + } + + /** + * Initialize a new KuzzleOptions instance and copy other KuzzleOptions fields + * + * @param options + */ + public KuzzleOptions(KuzzleOptions options) { + this.maxQueueSize = options.maxQueueSize; + this.minTokenDuration = options.minTokenDuration; + this.refreshedTokenDuration = options.refreshedTokenDuration; + this.autoResubscribe = options.autoResubscribe; + + this.maxRequestDelay = options.maxRequestDelay; + + this.queueFilter = options.queueFilter; + } + + /** + * @return The maximum amount of elements that the queue can contains. If set + * to -1, the size is unlimited. + */ + public int getMaxQueueSize() { + return maxQueueSize; + } + + /** + * Set the maximum amount of elements that the queue can contains. If set to + * -1, the size is unlimited. + * + * @param maxQueueSize + * @return This KuzzleOptions instance + */ + public KuzzleOptions setMaxQueueSize(int maxQueueSize) { + this.maxQueueSize = maxQueueSize < 0 ? -1 : maxQueueSize; + + return this; + } + + /** + * @return The minimum duration of a Token before being automatically + * refreshed. If set to -1 the SDK does not refresh the token + * automatically. + */ + public int getMinTokenDuration() { + return minTokenDuration; + } + + /** + * Set the minimum duration of a Token before being automatically refreshed. + * If set to -1 the SDK does not refresh the token automatically. + * + * @param minTokenDuration + * @return This KuzzleOptions instance + */ + public KuzzleOptions setMinTokenDuration(int minTokenDuration) { + this.minTokenDuration = minTokenDuration < 0 ? -1 : minTokenDuration; + + return this; + } + + /** + * @return The minimum duration of a Token after refresh. If set to -1 the SDK + * does not refresh the token automatically. + */ + public int getRefreshedTokenDuration() { + return refreshedTokenDuration; + } + + /** + * Set the minimum duration of a Token after refresh. If set to -1 the SDK + * does not refresh the token automatically. + * + * @param refreshedTokenDuration + * @return This KuzzleOptions instance + */ + public KuzzleOptions setRefreshedTokenDuration(int refreshedTokenDuration) { + this.refreshedTokenDuration = refreshedTokenDuration < 0 ? -1 + : refreshedTokenDuration; + + return this; + } + + /** + * @return The maximum delay between two requests to be replayed. + */ + public int getMaxRequestDelay() { + return maxRequestDelay; + } + + /** + * Set the maximum delay between two requests to be replayed. + * + * @param maxRequestDelay + * @return This KuzzleOptions instance + */ + public KuzzleOptions setMaxRequestDelay(int maxRequestDelay) { + this.maxRequestDelay = maxRequestDelay; + return this; + } + + public Predicate> getQueueFilter() { + return queueFilter; + } + + public KuzzleOptions setQueueFilter( + Predicate> filter) { + this.queueFilter = defaultValue(filter, + (ConcurrentHashMap obj) -> true); + return this; + } + + public boolean isAutoResubscribe() { + return autoResubscribe; + } + + public KuzzleOptions setAutoResubscribe(boolean autoResubscribe) { + this.autoResubscribe = autoResubscribe; + return this; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Options/Protocol/WebSocketOptions.java b/src/main/java/io/kuzzle/sdk/Options/Protocol/WebSocketOptions.java new file mode 100644 index 00000000..40c72496 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Options/Protocol/WebSocketOptions.java @@ -0,0 +1,145 @@ +package io.kuzzle.sdk.Options.Protocol; + +public class WebSocketOptions { + + /** + * The port to use to connect. + */ + private int port = 7512; + + /** + * If we use SSL connection. + */ + private boolean ssl = false; + + /** + * The duration before the connection timeout. + */ + private int connectionTimeout = -1; + + /** + * If the websocket auto reconnects. + */ + private boolean autoReconnect = true; + + /** + * The number of milliseconds between 2 automatic reconnection attempts. + */ + private long reconnectionDelay = 1000; + + /** + * The maximum number of automatic reconnection attempts. + */ + private long reconnectionRetries = 20; + + /** + * Initialize a new WebSocketOptions instance. + */ + public WebSocketOptions() { + } + + /** + * Initialize a new WebSocketOptions instance and copy other WebSocketOptions + * fields + * + * @param other + */ + public WebSocketOptions(WebSocketOptions other) { + this.port = other.port; + this.ssl = other.ssl; + this.connectionTimeout = other.connectionTimeout; + this.autoReconnect = other.autoReconnect; + this.reconnectionDelay = other.reconnectionDelay; + this.reconnectionRetries = other.reconnectionRetries; + } + + /** + * @return The port used to connect. + */ + public int getPort() { + return port; + } + + /** + * Set the port to use to connect. + * + * @param port + * @return This WebSocketOptions instance. + */ + public WebSocketOptions setPort(int port) { + this.port = port >= 0 ? port : 7512; + return this; + } + + /** + * @return If we use SSL connection. + */ + public boolean isSsl() { + return ssl; + } + + /** + * Set if we use SSL connection. + * + * @param ssl + * @return This WebSocketOptions instance. + */ + public WebSocketOptions setSsl(boolean ssl) { + this.ssl = ssl; + return this; + } + + /** + * @return The duration before the connection timeout. + */ + public int getConnectionTimeout() { + return connectionTimeout; + } + + /** + * Set the duration before the connection timeout. + * + * @param connectionTimeout + * @return This WebSocketOptions instance. + */ + public WebSocketOptions setConnectionTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout < 0 ? -1 : connectionTimeout; + return this; + } + + /** + * @return If the websocket auto reconnects. + */ + public boolean isAutoReconnect() { + return autoReconnect; + } + + /** + * Set if the websocket auto reconnects. + * + * @param autoReconnect + * @return This WebSocketOptions instance. + */ + public WebSocketOptions setAutoReconnect(boolean autoReconnect) { + this.autoReconnect = autoReconnect; + return this; + } + + public long getReconnectionDelay() { + return reconnectionDelay; + } + + public WebSocketOptions setReconnectionDelay(long reconnectionDelay) { + this.reconnectionDelay = reconnectionDelay; + return this; + } + + public long getReconnectionRetries() { + return reconnectionRetries; + } + + public WebSocketOptions setReconnectionRetries(long reconnectionRetries) { + this.reconnectionRetries = reconnectionRetries; + return this; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Options/SearchOptions.java b/src/main/java/io/kuzzle/sdk/Options/SearchOptions.java new file mode 100644 index 00000000..54d0badb --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Options/SearchOptions.java @@ -0,0 +1,59 @@ +package io.kuzzle.sdk.Options; + +import java.util.concurrent.ConcurrentHashMap; + +public class SearchOptions { + + private Integer from; + private String scroll; + private Integer size; + /** + * Constructor + */ + public SearchOptions() {} + + /** + * Copy constructor + * + * @param options + */ + public SearchOptions(SearchOptions options) { + this.from = options.getFrom(); + this.scroll = options.getScroll(); + this.size = options.getSize(); + } + + public Integer getFrom() { + return from; + } + + public Integer getSize() { + return size; + } + + public String getScroll() { + return scroll; + } + + public void setFrom(Integer from) { + this.from = from; + } + + public void setSize(Integer size) { + this.size = size; + } + + public void setScroll(String scroll) { + this.scroll = scroll; + } + + public ConcurrentHashMap toHashMap() { + ConcurrentHashMap options = new ConcurrentHashMap<>(); + + options.put("from", this.from); + options.put("scroll", this.scroll); + options.put("size", this.size); + + return options; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Options/SubscribeOptions.java b/src/main/java/io/kuzzle/sdk/Options/SubscribeOptions.java new file mode 100644 index 00000000..8ba87018 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Options/SubscribeOptions.java @@ -0,0 +1,102 @@ +package io.kuzzle.sdk.Options; + +import java.util.concurrent.ConcurrentHashMap; + +public class SubscribeOptions { + public enum Scope { + ALL("all"), + IN("in"), + OUT("out"), + NONE("none"); + + private final String label; + private Scope(final String label) { + this.label = label; + } + + @Override + public String toString() { + return this.label; + } + } + public enum Users { + ALL("all"), + IN("in"), + OUT("out"), + NONE("none"); + + private final String label; + private Users(final String label) { + this.label = label; + } + + @Override + public String toString() { + return this.label; + } + } + private Scope scope = Scope.ALL; + private Users users = Users.NONE; + private boolean subscribeToSelf = true; + private ConcurrentHashMap volatiles = new ConcurrentHashMap<>(); + + /** + * Constructor + */ + public SubscribeOptions() {} + + /** + * Copy constructor + * + * @param options + */ + public SubscribeOptions(SubscribeOptions options) { + this.scope = options.getScope(); + this.users = options.getUsers(); + this.subscribeToSelf = options.isSubscribeToSelf(); + this.volatiles = options.getVolatiles(); + } + + public Scope getScope() { + return scope; + } + + public void setScope(Scope scope) { + this.scope = scope; + } + + public Users getUsers() { + return users; + } + + public void setUsers(Users users) { + this.users = users; + } + + public boolean isSubscribeToSelf() { + return subscribeToSelf; + } + + public void setSubscribeToSelf(boolean subscribeToSelf) { + this.subscribeToSelf = subscribeToSelf; + } + + public ConcurrentHashMap getVolatiles() { + return volatiles; + } + + public void setVolatiles(ConcurrentHashMap volatiles) { + this.volatiles = volatiles; + } + + public ConcurrentHashMap toHashMap() { + ConcurrentHashMap options = new ConcurrentHashMap<>(); + + options.put("scope", this.scope.toString()); + options.put("users", this.users.toString()); + options.put("subscribeToSelf", this.subscribeToSelf); + options.put("volatile", this.volatiles); + + return options; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Options/UpdateOptions.java b/src/main/java/io/kuzzle/sdk/Options/UpdateOptions.java new file mode 100644 index 00000000..9bf7d2e2 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Options/UpdateOptions.java @@ -0,0 +1,59 @@ +package io.kuzzle.sdk.Options; + +import java.util.concurrent.ConcurrentHashMap; + +public class UpdateOptions { + + private Integer retryOnConflict; + private Boolean source; + private Boolean waitForRefresh; + /** + * Constructor + */ + public UpdateOptions() {} + + /** + * Copy constructor + * + * @param options + */ + public UpdateOptions(UpdateOptions options) { + this.waitForRefresh = options.getWaitForRefresh(); + this.retryOnConflict = options.getRetryOnConflict(); + this.source = options.getSource(); + } + + public Boolean getWaitForRefresh() { + return waitForRefresh; + } + + public int getRetryOnConflict() { + return retryOnConflict; + } + + public Boolean getSource() { + return source; + } + + public void setWaitForRefresh(Boolean waitForRefresh) { + this.waitForRefresh = waitForRefresh; + } + + public void setRetryOnConflict(int retryOnConflict) { + this.retryOnConflict = retryOnConflict; + } + + public void setSource(Boolean source) { + this.source = source; + } + + public ConcurrentHashMap toHashMap() { + ConcurrentHashMap options = new ConcurrentHashMap<>(); + + options.put("source", this.source); + options.put("waitForRefresh", this.waitForRefresh); + options.put("retryOnConflict", this.retryOnConflict); + + return options; + } +} diff --git a/src/main/java/io/kuzzle/sdk/Protocol/AbstractProtocol.java b/src/main/java/io/kuzzle/sdk/Protocol/AbstractProtocol.java new file mode 100644 index 00000000..49711726 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Protocol/AbstractProtocol.java @@ -0,0 +1,32 @@ +package io.kuzzle.sdk.Protocol; + +import io.kuzzle.sdk.Events.EventManager; +import java.util.concurrent.ConcurrentHashMap; + +public abstract class AbstractProtocol extends EventManager { + /** + * Current connection state. + * + * @return The state. + */ + public abstract ProtocolState getState(); + + /** + * connect this instance. + * + * @throws Exception + */ + public abstract void connect() throws Exception; + + /** + * Disconnect this instance. + */ + public abstract void disconnect(); + + /** + * Send the specified payload to Kuzzle. + * + * @param payload + */ + public abstract void send(ConcurrentHashMap payload); +} diff --git a/src/main/java/io/kuzzle/sdk/Protocol/ProtocolState.java b/src/main/java/io/kuzzle/sdk/Protocol/ProtocolState.java new file mode 100644 index 00000000..e53af578 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Protocol/ProtocolState.java @@ -0,0 +1,7 @@ +package io.kuzzle.sdk.Protocol; + +public enum ProtocolState { + CLOSE, // The network protocol does not accept requests. + OPEN, // The network protocol accepts new requests. + RECONNECTING, +} diff --git a/src/main/java/io/kuzzle/sdk/Protocol/WebSocket.java b/src/main/java/io/kuzzle/sdk/Protocol/WebSocket.java new file mode 100644 index 00000000..89e7cf02 --- /dev/null +++ b/src/main/java/io/kuzzle/sdk/Protocol/WebSocket.java @@ -0,0 +1,232 @@ +package io.kuzzle.sdk.Protocol; + +import com.neovisionaries.ws.client.WebSocketAdapter; +import com.neovisionaries.ws.client.WebSocketException; +import com.neovisionaries.ws.client.WebSocketFactory; +import com.neovisionaries.ws.client.WebSocketFrame; +import io.kuzzle.sdk.CoreClasses.Json.JsonSerializer; +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; + +import javax.net.ssl.SSLSocketFactory; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.LinkedBlockingDeque; + +public class WebSocket extends AbstractProtocol { + + protected final boolean ssl; + protected final int port; + protected BlockingDeque> queue; + protected com.neovisionaries.ws.client.WebSocket socket; + protected ProtocolState state = ProtocolState.CLOSE; + protected URI uri; + protected int connectionTimeout; + protected boolean autoReconnect; + protected long reconnectionDelay; + protected long reconnectionRetries; + + public WebSocket(URI uri) throws Exception { + WebSocketOptions options = new WebSocketOptions(); + if (uri.getPort() > -1) { + options.setPort(uri.getPort()); + } + if (uri.getHost() == null || uri.getHost().isEmpty()) { + throw new URISyntaxException("Missing host", "Could not find host part"); + } + if (uri.getScheme() != null) { + options.setSsl(uri.getScheme().equals("wss")); + } + WebSocketOptions wsOptions = options != null ? new WebSocketOptions(options) + : new WebSocketOptions(); + + ssl = wsOptions.isSsl(); + port = wsOptions.getPort(); + connectionTimeout = wsOptions.getConnectionTimeout(); + autoReconnect = wsOptions.isAutoReconnect(); + reconnectionDelay = wsOptions.getReconnectionDelay(); + reconnectionRetries = wsOptions.getReconnectionRetries(); + + this.uri = new URI( + (ssl ? "wss" : "ws") + "://" + uri.getHost() + ":" + port + "/"); + this.queue = new LinkedBlockingDeque<>(); + } + + public WebSocket(URI uri, WebSocketOptions options) + throws URISyntaxException, IllegalArgumentException { + this(uri.getHost(), options); + } + + public WebSocket(String host) + throws IllegalArgumentException, URISyntaxException { + this(host, new WebSocketOptions()); + } + + /** + * @param host Kuzzle host address + * @param options WebSocket options + * @throws URISyntaxException + * @throws IllegalArgumentException + */ + public WebSocket(String host, WebSocketOptions options) + throws URISyntaxException, IllegalArgumentException { + super(); + + WebSocketOptions wsOptions = options != null ? new WebSocketOptions(options) + : new WebSocketOptions(); + + ssl = wsOptions.isSsl(); + port = wsOptions.getPort(); + connectionTimeout = wsOptions.getConnectionTimeout(); + autoReconnect = wsOptions.isAutoReconnect(); + reconnectionDelay = wsOptions.getReconnectionDelay(); + reconnectionRetries = wsOptions.getReconnectionRetries(); + + if (host == null || host.isEmpty()) { + throw new IllegalArgumentException("Host name/address can't be empty"); + } + this.uri = new URI((ssl ? "wss" : "ws") + "://" + host + ":" + port + "/"); + this.queue = new LinkedBlockingDeque<>(); + } + + public ProtocolState getState() { + return state; + } + + @Override + public void send(ConcurrentHashMap payload) { + queue.add(payload); + } + + protected com.neovisionaries.ws.client.WebSocket createClientSocket() + throws IOException { + WebSocketFactory wsFactory = new WebSocketFactory(); + + if (connectionTimeout > -1) { + wsFactory = wsFactory.setConnectionTimeout(connectionTimeout); + } + + if (ssl) { + + wsFactory.setSocketFactory(SSLSocketFactory.getDefault()); + } + + return wsFactory.createSocket(uri); + } + + /** + * Connects to a Kuzzle server. + * + * @throws IOException + * @throws WebSocketException + * @throws Exception + */ + @Override + public void connect() throws IOException, WebSocketException { + if (socket != null) { + return; + } + + socket = createClientSocket(); + + socket.connect(); + state = ProtocolState.OPEN; + super.trigger(Event.networkStateChange, state); + Dequeue(); + + socket.addListener(new WebSocketAdapter() { + @Override + public void onTextMessage( + com.neovisionaries.ws.client.WebSocket websocket, String text) + throws Exception { + super.onTextMessage(websocket, text); + WebSocket.super.trigger(Event.networkResponseReceived, text); + } + + @Override + public void onDisconnected(com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame serverCloseFrame, + WebSocketFrame clientCloseFrame, + boolean closedByServer) { + socket.clearListeners(); + socket = null; + CloseState(autoReconnect); + } + }); + } + + private void tryToReconnect() { + if (state == ProtocolState.RECONNECTING) { + return; + } + + state = ProtocolState.RECONNECTING; + super.trigger(Event.networkStateChange, state); + for (int i = 0; i < reconnectionRetries; i++) { + try { + connect(); + break; + } catch (WebSocketException e) { + try { + socket = null; + Thread.sleep(reconnectionDelay); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } catch (IOException e) { + try { + socket = null; + Thread.sleep(reconnectionDelay); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } + } + } + + /** + * Disconnects this instance. + */ + @Override + public void disconnect() { + CloseState(false); + } + + synchronized protected void CloseState(final boolean tryToReconnect) { + if (state != ProtocolState.CLOSE) { + if (tryToReconnect) { + tryToReconnect(); + } else { + socket.disconnect(); + state = ProtocolState.CLOSE; + socket = null; + super.trigger(Event.networkStateChange, state); + } + } + } + + protected Thread Dequeue() { + Thread thread = new Thread(() -> { + while (state == ProtocolState.OPEN) { + ConcurrentHashMap payload = queue.poll(); + if (payload != null) { + String rawJson = JsonSerializer.serialize(payload); + socket.sendText(rawJson); + } + } + }); + thread.start(); + return thread; + } + + public int getConnectionTimeout() { + return connectionTimeout; + } + + public void setConnectionTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout < 0 ? -1 : connectionTimeout; + } +} diff --git a/src/main/java/io/kuzzle/sdk/core/Collection.java b/src/main/java/io/kuzzle/sdk/core/Collection.java deleted file mode 100644 index a9884ff5..00000000 --- a/src/main/java/io/kuzzle/sdk/core/Collection.java +++ /dev/null @@ -1,1975 +0,0 @@ -package io.kuzzle.sdk.core; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.SubscribeListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.SearchResult; -import io.kuzzle.sdk.responses.NotificationResponse; - -public class Collection { - private final Kuzzle kuzzle; - private final String collection; - private final String index; - private ResponseListener subscribeCallback; - private JSONObject subscribeError = null; - private Room subscribeRoom = null; - - protected JSONObject headers; - - /** - * Constructor - * - * @param kuzzle Kuzzle instance - * @param collection Data collection name - * @param index Parent data index name - */ - public Collection(final Kuzzle kuzzle, final String collection, final String index) { - if (kuzzle == null) { - throw new IllegalArgumentException("Collection: need a Kuzzle instance to initialize"); - } - - if (index == null || collection == null) { - throw new IllegalArgumentException("Collection: index and collection required"); - } - this.kuzzle = kuzzle; - this.collection = collection; - this.index = index; - - try { - this.headers = new JSONObject(kuzzle.getHeaders().toString()); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #search(JSONObject, Options, ResponseListener)} - */ - public void search(final JSONObject filter, final ResponseListener listener) { - this.search(filter, new Options(), listener); - } - - /** - * Executes a search on the data collection. - * /!\ There is a small delay between documents creation and their existence in our search layer, - * usually a couple of seconds. - * That means that a document that was just been created won’t be returned by this function. - * - * @param filters Search filters to apply - * @param options Request options - * @param listener Response callback listener - */ - public void search(final JSONObject filters, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("listener cannot be null"); - } - this.kuzzle.isValid(); - JSONObject data = new JSONObject(); - try { - if (filters != null) { - data.put("body", filters); - } - - this.kuzzle.addHeaders(data, this.getHeaders()); - - this.kuzzle.query(makeQueryArgs("document", "search"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - try { - SearchResult response; - JSONObject aggregations = null; - JSONArray hits = object.getJSONObject("result").getJSONArray("hits"); - List docs = new ArrayList(); - - for (int i = 0; i < hits.length(); i++) { - JSONObject hit = hits.getJSONObject(i); - Document doc = new Document(Collection.this, hit.getString("_id"), hit.getJSONObject("_source"), hit.getJSONObject("_meta")); - - docs.add(doc); - } - - if (object.getJSONObject("result").has("_scroll_id")) { - options.setScrollId(object.getJSONObject("result").getString("_scroll_id")); - } - - if (object.getJSONObject("result").has("aggregations")) { - aggregations = object.getJSONObject("result").getJSONObject("aggregations"); - } - - response = new SearchResult( - Collection.this, - object.getJSONObject("result").getInt("total"), - docs, - aggregations, - options, - filters, - options.getPrevious() - ); - - listener.onSuccess(response); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #scroll(String, Options, ResponseListener)} - */ - public void scroll(String scrollId, final ResponseListener listener) { - this.scroll(scrollId, new Options(), new JSONObject(), listener); - } - - /** - * {@link #scroll(String, Options, ResponseListener)} - */ - public void scroll(String scrollId, final Options options, final ResponseListener listener) { - this.scroll(scrollId, options, new JSONObject(), listener); - } - - /** - * Gets the next page of results from a previous search or scroll request - * - * @param scrollId Scroll unique identifier - * @param options Request options - * @param listener Response callback listener - */ - public void scroll(String scrollId, final Options options, final JSONObject filters, final ResponseListener listener) { - JSONObject request; - - try { - request = new JSONObject().put("body", new JSONObject()); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - - if (listener == null) { - throw new IllegalArgumentException("listener cannot be null"); - } - - if (scrollId == null) { - throw new RuntimeException("Collection.scroll: scrollId is required"); - } - - options.setScrollId(scrollId); - - try { - this.kuzzle.query(this.kuzzle.buildQueryArgs("document", "scroll"), request, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - try { - SearchResult response; - JSONArray hits = object.getJSONObject("result").getJSONArray("hits"); - List docs = new ArrayList(); - - for (int i = 0; i < hits.length(); i++) { - JSONObject hit = hits.getJSONObject(i); - Document doc = new Document(Collection.this, hit.getString("_id"), hit.getJSONObject("_source"), hit.getJSONObject("_meta")); - - docs.add(doc); - } - - if (object.getJSONObject("result").has("_scroll_id")) { - options.setScrollId(object.getJSONObject("result").getString("_scroll_id")); - } - - response = new SearchResult( - Collection.this, - object.getJSONObject("result").getInt("total"), - docs, - new JSONObject(), - options, - filters, - options.getPrevious() - ); - - listener.onSuccess(response); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #scrollSpecifications(String, Options, ResponseListener)} - */ - public void scrollSpecifications(final String scrollId, final ResponseListener listener) { - this.scrollSpecifications(scrollId, new Options(), listener); - } - - /** - * Scrolls through specifications using the provided scrollId - * - * @param scrollId Scroll unique identifier - * @param options Request options - * @param listener Response callback listener - */ - public void scrollSpecifications(final String scrollId, final Options options, final ResponseListener listener) { - this.kuzzle.isValid(); - - JSONObject data = new JSONObject(); - - if (scrollId == null) { - throw new RuntimeException("Collection.scrollSpecifications: scrollId is required"); - } - - if (listener == null) { - throw new IllegalArgumentException("listener cannot be null"); - } - - try { - data.put("scrollId", scrollId); - - this.kuzzle.addHeaders(data, this.getHeaders()); - - this.kuzzle.query(makeQueryArgs("collection", "scrollSpecifications"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #searchSpecifications(JSONObject, Options, ResponseListener)} - */ - public void searchSpecifications(final ResponseListener listener) { - this.searchSpecifications(null, new Options(), listener); - } - - /** - * {@link #searchSpecifications(JSONObject, Options, ResponseListener)} - */ - public void searchSpecifications(final JSONObject filters, final ResponseListener listener) { - this.searchSpecifications(filters, new Options(), listener); - } - - /** - * {@link #searchSpecifications(JSONObject, Options, ResponseListener)} - */ - public void searchSpecifications(final Options options, final ResponseListener listener) { - this.searchSpecifications(null, options, listener); - } - - /** - * Searches specifications across indexes/collections according to the provided filters - * - * @param filters Optional filters in ElasticSearch Query DSL format - * @param options Request options - * @param listener Response callback listener - */ - public void searchSpecifications(final JSONObject filters, final Options options, final ResponseListener listener) { - this.kuzzle.isValid(); - - JSONObject data = new JSONObject(); - - if (listener == null) { - throw new IllegalArgumentException("listener cannot be null"); - } - - try { - if (filters != null) { - data.put("body", new JSONObject() - .put("query", filters) - ); - } - - this.kuzzle.addHeaders(data, this.getHeaders()); - - this.kuzzle.query(makeQueryArgs("collection", "searchSpecifications"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * Make query args kuzzle . query args. - * - * @param controller API Controller to invoke - * @param action Controller action name - * @return Built query arguments - */ - protected io.kuzzle.sdk.core.Kuzzle.QueryArgs makeQueryArgs(final String controller, final String action) { - io.kuzzle.sdk.core.Kuzzle.QueryArgs args = new io.kuzzle.sdk.core.Kuzzle.QueryArgs(); - args.action = action; - args.controller = controller; - args.index = this.index; - args.collection = this.collection; - return args; - } - - /** - * Returns the provided array of Documents with each one being serialized - * - * @param documents Array of Document objects - * @return A list of serialized documents - */ - private JSONArray serializeDocuments(Document[] documents) throws JSONException { - JSONArray serializedDocuments = new JSONArray(); - - for (Document document : documents) { - serializedDocuments.put(document.serialize()); - } - - return serializedDocuments; - } - - /** - * {@link #count(JSONObject, Options, ResponseListener)} - */ - public void count(final JSONObject filters, final ResponseListener listener) { - this.count(filters, null, listener); - } - - /** - * {@link #count(JSONObject, Options, ResponseListener)} - */ - public void count(final ResponseListener listener) { - this.count(null, null, listener); - } - - /** - * Returns the number of documents matching the provided set of filters. - * There is a small delay between documents creation and their existence in our search layer, - * usually a couple of seconds. - * That means that a document that was just been created won’t be returned by this function - * - * @param filters Search filters - * @param options Request options - * @param listener Response callback listener - */ - public void count(final JSONObject filters, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Collection.count: listener required"); - } - JSONObject data = new JSONObject(); - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - data.put("body", filters); - this.kuzzle.query(makeQueryArgs("document", "count"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result").getInt("count")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #create(JSONObject, Options, ResponseListener)} - */ - public Collection create(final Options options) { - return this.create(null, options, null); - } - - /** - * {@link #create(JSONObject, Options, ResponseListener)} - */ - public Collection create() { - return this.create(null, null, null); - } - - /** - * {@link #create(JSONObject, Options, ResponseListener)} - */ - public Collection create(final ResponseListener listener) { - return this.create(null, null, listener); - } - - /** - * {@link #create(JSONObject, Options, ResponseListener)} - */ - public Collection create(final Options options, final ResponseListener listener) { - return this.create(null, options, listener); - } - - /** - * {@link #create(JSONObject, Options, ResponseListener)} - */ - public Collection create(final JSONObject mapping) { - return this.create(mapping, null, null); - } - - /** - * {@link #create(JSONObject, Options, ResponseListener)} - */ - public Collection create(final JSONObject mapping, final Options options) { - return this.create(mapping, options, null); - } - - /** - * {@link #create(JSONObject, Options, ResponseListener)} - */ - public Collection create(final JSONObject mapping, final ResponseListener listener) { - return this.create(mapping, null, listener); - } - - /** - * Create a new empty data collection, with associated mappings. - * Kuzzle automatically creates data collections when storing documents, - * but there are cases where we want to create and prepare data collections - * before storing documents in it. - * - * @param mapping Collection mapping - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection create(final JSONObject mapping, final Options options, final ResponseListener listener) { - JSONObject data = new JSONObject(); - - try { - if (mapping != null) { - data.put("body", mapping); - } - - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("collection", "create"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #createDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection createDocument(final String id, final JSONObject content) throws JSONException { - return this.createDocument(id, content, null, null); - } - - /** - * {@link #createDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection createDocument(final String id, final JSONObject content, Options options) throws JSONException { - return this.createDocument(id, content, options, null); - } - - /** - * {@link #createDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection createDocument(final String id, final JSONObject content, final ResponseListener listener) throws JSONException { - return this.createDocument(id, content, null, listener); - } - - /** - * {@link #createDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection createDocument(final JSONObject content) throws JSONException { - return this.createDocument(null, content, null, null); - } - - /** - * {@link #createDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection createDocument(final JSONObject content, Options options) throws JSONException { - return this.createDocument(null, content, options, null); - } - - /** - * {@link #createDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection createDocument(final JSONObject content, final ResponseListener listener) throws JSONException { - return this.createDocument(null, content, null, listener); - } - - /** - * {@link #createDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection createDocument(final JSONObject content, Options options, final ResponseListener listener) throws JSONException { - return this.createDocument(null, content, options, listener); - } - - /** - * Create document kuzzle data collection. - * - * @param id document ID - * @param content document content - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Collection createDocument(final String id, final JSONObject content, Options options, final ResponseListener listener) throws JSONException { - if (content == null) { - throw new IllegalArgumentException("Cannot create an empty document"); - } - - Document doc = new Document(this, id, content); - return this.createDocument(doc, options, listener); - } - - /** - * {@link #createDocument(Document, Options, ResponseListener)} - */ - public Collection createDocument(final Document document) { - return this.createDocument(document, null, null); - } - - /** - * {@link #createDocument(Document, Options, ResponseListener)} - */ - public Collection createDocument(final Document document, final Options options) { - return this.createDocument(document, options, null); - } - - /** - * {@link #createDocument(Document, Options, ResponseListener)} - */ - public Collection createDocument(final Document document, final ResponseListener listener) { - return this.createDocument(document, null, listener); - } - - /** - * Create a new document in kuzzle - * - * @param document the document - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection createDocument(final Document document, final Options options, final ResponseListener listener) { - String action = "create"; - JSONObject data = document.serialize(); - - if (options != null && options.getIfExist().equals("replace")) { - action = "createOrReplace"; - } - - this.kuzzle.addHeaders(data, this.getHeaders()); - - try { - this.kuzzle.query(makeQueryArgs("document", action), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - JSONObject result = response.getJSONObject("result"); - Document document = new Document(Collection.this, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta")); - document.setVersion(result.getLong("_version")); - listener.onSuccess(document); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #collectionMapping(JSONObject)} - */ - public CollectionMapping collectionMapping() { - return new CollectionMapping(this); - } - - /** - * CollectionMapping constructor, attaching it to this - * Collection object - * - * @param mapping Raw mapping to declare - * @return a newly instantiated CollectionMapping object - */ - public CollectionMapping collectionMapping(JSONObject mapping) { - return new CollectionMapping(this, mapping); - } - - /** - * {@link #deleteDocument(String, Options, ResponseListener)} - */ - public Collection deleteDocument(final String documentId) { - return this.deleteDocument(documentId, null, null); - } - - /** - * {@link #deleteDocument(String, Options, ResponseListener)} - */ - public Collection deleteDocument(final String documentId, Options options) { - return this.deleteDocument(documentId, options, null); - } - - /** - * {@link #deleteDocument(String, Options, ResponseListener)} - */ - public Collection deleteDocument(final String documentId, final ResponseListener listener) { - return this.deleteDocument(documentId, null, listener); - } - - /** - * Delete a single document - * - * @param documentId Document unique identifier - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection deleteDocument(final String documentId, final Options options, final ResponseListener listener) { - if (documentId == null) { - throw new IllegalArgumentException("Collection.deleteDocument: documentId required"); - } - return this.deleteDocument(documentId, null, options, listener, null); - } - - /** - * {@link #deleteDocument(JSONObject, Options, ResponseListener)} - */ - public Collection deleteDocument(final JSONObject filters) { - return this.deleteDocument(filters, null, null); - } - - /** - * {@link #deleteDocument(JSONObject, Options, ResponseListener)} - */ - public Collection deleteDocument(final JSONObject filters, final Options options) { - return this.deleteDocument(filters, options, null); - } - - /** - * {@link #deleteDocument(JSONObject, Options, ResponseListener)} - */ - public Collection deleteDocument(final JSONObject filters, final ResponseListener listener) { - return this.deleteDocument(filters, null, listener); - } - - /** - * Delete documents using search filters - * - * @param filters Search filters - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection deleteDocument(final JSONObject filters, final Options options, final ResponseListener listener) { - if (filters == null) { - throw new IllegalArgumentException("Collection.deleteDocument: filters required"); - } - return this.deleteDocument(null, filters, options, null, listener); - } - - /** - * Delete either a single document or multiple ones using search filters - * - * @param documentId Document unique identifier - * @param filter Search fitlers - * @param options Request options - * @param listener Response callback listener (single document delete) - * @param listener2 Response callback listener (document search delete) - * @return this - */ - protected Collection deleteDocument(final String documentId, final JSONObject filter, final Options options, final ResponseListener listener, final ResponseListener listener2) { - JSONObject data = new JSONObject(); - String action; - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - if (documentId != null) { - data.put("_id", documentId); - action = "delete"; - } else { - data.put("body", new JSONObject().put("query", filter)); - action = "deleteByQuery"; - } - this.kuzzle.query(makeQueryArgs("document", action), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (listener != null) { - listener.onSuccess(response.getJSONObject("result").getString("_id")); - } else if (listener2 != null) { - JSONArray array = response.getJSONObject("result").getJSONArray("hits"); - int length = array.length(); - String[] ids = new String[length]; - for (int i = 0; i < length; i++) { - ids[i] = array.getString(i); - } - listener2.onSuccess(ids); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } else if (listener2 != null) { - listener2.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #deleteSpecifications(Options, ResponseListener)} - */ - public Collection deleteSpecifications() throws JSONException { - return this.deleteSpecifications(new Options(), null); - } - - /** - * {@link #deleteSpecifications(Options, ResponseListener)} - */ - public Collection deleteSpecifications(final Options options) throws JSONException { - return this.deleteSpecifications(options, null); - } - - /** - * {@link #deleteSpecifications(Options, ResponseListener)} - */ - public Collection deleteSpecifications(final ResponseListener listener) throws JSONException { - return this.deleteSpecifications(new Options(), listener); - } - - /** - * Deletes the current specifications for this collection - * - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Collection deleteSpecifications(final Options options, final ResponseListener listener) throws JSONException { - JSONObject data = new JSONObject(); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("collection", "deleteSpecifications"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #document(String, JSONObject)} - */ - public Document document() throws JSONException { - return new Document(this); - } - - /** - * {@link #document(String, JSONObject)} - */ - public Document document(final String id) throws JSONException { - return new Document(this, id); - } - - /** - * {@link #document(String, JSONObject)} - */ - public Document document(final JSONObject content) throws JSONException { - return new Document(this, content); - } - - /** - * Instantiates a Document object with a preset unique - * identifier and content. - * This document is attached to this data collection - * - * @param id Document unique identifier - * @param content Document content - * @return newly instantiated Document object - * @throws JSONException - */ - public Document document(final String id, final JSONObject content) throws JSONException { - return new Document(this, id, content); - } - - /** - * {@link #documentExists(String, Options, ResponseListener)} - */ - public void documentExists(final String documentId, final ResponseListener listener) { - this.documentExists(documentId, null, listener); - } - - /** - * Asks Kuzzle API if the provided document exists - * - * @param documentId Document unique identifier - * @param options Request options - * @param listener Response callback listener - */ - public void documentExists(final String documentId, final Options options, final ResponseListener listener) { - if (documentId == null) { - throw new IllegalArgumentException("Collection.documentExists: documentId required"); - } - if (listener == null) { - throw new IllegalArgumentException("Collection.documentExists: listener required"); - } - - try { - JSONObject data = new JSONObject().put("_id", documentId); - this.kuzzle.addHeaders(data, this.getHeaders()); - - this.kuzzle.query(makeQueryArgs("document", "exists"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - listener.onSuccess(response); - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #fetchDocument(String, Options, ResponseListener)} - */ - public void fetchDocument(final String documentId, final ResponseListener listener) { - this.fetchDocument(documentId, null, listener); - } - - /** - * Fetch a document from Kuzzle - * - * @param documentId Document unique identifier - * @param options Request options - * @param listener Response callback listener - */ - public void fetchDocument(final String documentId, final Options options, final ResponseListener listener) { - if (documentId == null) { - throw new IllegalArgumentException("Collection.fetchDocument: documentId required"); - } - if (listener == null) { - throw new IllegalArgumentException("Collection.fetchDocument: listener required"); - } - - try { - JSONObject data = new JSONObject().put("_id", documentId); - this.kuzzle.addHeaders(data, this.getHeaders()); - - this.kuzzle.query(makeQueryArgs("document", "get"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - Document document = new Document(Collection.this, result.getString("_id"), result.getJSONObject("_source")); - - document.setVersion(result.getLong("_version")); - listener.onSuccess(document); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #getMapping(Options, ResponseListener)} - */ - public void getMapping(final ResponseListener listener) { - this.getMapping(null, listener); - } - - /** - * Get the mapping for this data collection - * - * @param options Request options - * @param listener Response callback listener - */ - public void getMapping(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Collection.getMapping: listener required"); - } - new CollectionMapping(this).refresh(options, listener); - } - - /** - * {@link #getSpecifications(Options, ResponseListener)} - */ - public void getSpecifications(final ResponseListener listener) throws JSONException { - this.getSpecifications(new Options(), listener); - } - - /** - * Get the specifications for this collection - * - * @param options Request options - * @param listener Response callback listener - * @throws JSONException - */ - public void getSpecifications(final Options options, final ResponseListener listener) throws JSONException { - JSONObject data = new JSONObject() - .put("body", new JSONObject()); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("collection", "getSpecifications"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * Create multiple documents - * - * @param documents Array of Document objects to create - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Collection mCreateDocument(final Document[] documents, final Options options, final ResponseListener listener) throws JSONException { - if (documents.length == 0) { - throw new IllegalArgumentException("Collection.mCreateDocument: The document array should not be empty"); - } - - JSONObject data = new JSONObject() - .put("body", new JSONObject() - .put("documents", this.serializeDocuments(documents)) - ); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("document", "mCreate"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #mCreateDocument(Document[], Options, ResponseListener)} - */ - public Collection mCreateDocument(final Document[] documents, final ResponseListener listener) throws JSONException { - return this.mCreateDocument(documents, new Options(), listener); - } - - /** - * {@link #mCreateDocument(Document[], Options, ResponseListener)} - */ - public Collection mCreateDocument(final Document[] documents, Options options) throws JSONException { - return this.mCreateDocument(documents, options, null); - } - - /** - * {@link #mCreateDocument(Document[], Options, ResponseListener)} - */ - public Collection mCreateDocument(final Document[] documents) throws JSONException { - return this.mCreateDocument(documents, new Options(), null); - } - - /** - * Create or replace multiple documents - * - * @param documents Array of Document objects to create or replace - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Collection mCreateOrReplaceDocument(final Document[] documents, final Options options, final ResponseListener listener) throws JSONException { - if (documents.length == 0) { - throw new IllegalArgumentException("Collection.mCreateOrReplaceDocument: The document array should not be empty"); - } - - JSONObject data = new JSONObject() - .put("body", new JSONObject() - .put("documents", this.serializeDocuments(documents)) - ); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("document", "mCreateOrReplace"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #mCreateOrReplaceDocument(Document[], Options, ResponseListener)} - */ - public Collection mCreateOrReplaceDocument(final Document[] documents, final ResponseListener listener) throws JSONException { - return this.mCreateOrReplaceDocument(documents, new Options(), listener); - } - - /** - * {@link #mCreateOrReplaceDocument(Document[], Options, ResponseListener)} - */ - public Collection mCreateOrReplaceDocument(final Document[] documents, Options options) throws JSONException { - return this.mCreateOrReplaceDocument(documents, options, null); - } - - /** - * {@link #mCreateOrReplaceDocument(Document[], Options, ResponseListener)} - */ - public Collection mCreateOrReplaceDocument(final Document[] documents) throws JSONException { - return this.mCreateOrReplaceDocument(documents, new Options(), null); - } - - /** - * Delete multiple documents using their unique IDs - * - * @param documentIds Array of document IDs to delete - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Collection mDeleteDocument(final String[] documentIds, final Options options, final ResponseListener listener) throws JSONException { - if (documentIds.length == 0) { - throw new IllegalArgumentException("Collection.mDeleteDocument: The document IDs array should not be empty"); - } - - JSONObject data = new JSONObject() - .put("body", new JSONObject() - .put("ids", new JSONArray(Arrays.asList(documentIds))) - ); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("document", "mDelete"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONArray("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #mDeleteDocument(String[], Options, ResponseListener)} - */ - public Collection mDeleteDocument(final String[] documentIds, final ResponseListener listener) throws JSONException { - return this.mDeleteDocument(documentIds, new Options(), listener); - } - - /** - * {@link #mDeleteDocument(String[], Options, ResponseListener)} - */ - public Collection mDeleteDocument(final String[] documentIds, Options options) throws JSONException { - return this.mDeleteDocument(documentIds, options, null); - } - - /** - * {@link #mDeleteDocument(String[], Options, ResponseListener)} - */ - public Collection mDeleteDocument(final String[] documentIds) throws JSONException { - return this.mDeleteDocument(documentIds, new Options(), null); - } - - /** - * Fetch multiple documents - * - * @param documentIds Array of document IDs to retrieve - * @param options Request options - * @param listener Response callback listener - * @throws JSONException - */ - public void mGetDocument(final String[] documentIds, final Options options, final ResponseListener listener) throws JSONException { - if (documentIds.length == 0) { - throw new IllegalArgumentException("Collection.mGetDocument: The document IDs array should not be empty"); - } - - JSONObject data = new JSONObject() - .put("body", new JSONObject() - .put("ids", new JSONArray(Arrays.asList(documentIds))) - ); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("document", "mGet"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #mGetDocument(String[], Options, ResponseListener)} - */ - public void mGetDocument(final String[] documentIds, final ResponseListener listener) throws JSONException { - this.mGetDocument(documentIds, new Options(), listener); - } - - /** - * Replace multiple documents - * - * @param documents Array of Document objects to replace - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Collection mReplaceDocument(final Document[] documents, final Options options, final ResponseListener listener) throws JSONException { - if (documents.length == 0) { - throw new IllegalArgumentException("Collection.mReplaceDocument: The document array should not be empty"); - } - - JSONObject data = new JSONObject() - .put("body", new JSONObject() - .put("documents", this.serializeDocuments(documents)) - ); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("document", "mReplace"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #mReplaceDocument(Document[], Options, ResponseListener)} - */ - public Collection mReplaceDocument(final Document[] documents, final ResponseListener listener) throws JSONException { - return this.mReplaceDocument(documents, new Options(), listener); - } - - /** - * {@link #mReplaceDocument(Document[], Options, ResponseListener)} - */ - public Collection mReplaceDocument(final Document[] documents, Options options) throws JSONException { - return this.mReplaceDocument(documents, options, null); - } - - /** - * {@link #mReplaceDocument(Document[], Options, ResponseListener)} - */ - public Collection mReplaceDocument(final Document[] documents) throws JSONException { - return this.mReplaceDocument(documents, new Options(), null); - } - - /** - * Update multiple documents - * - * @param documents Array of Document objects to update - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Collection mUpdateDocument(final Document[] documents, final Options options, final ResponseListener listener) throws JSONException { - if (documents.length == 0) { - throw new IllegalArgumentException("Collection.mUpdateDocument: The document array should not be empty"); - } - - JSONObject data = new JSONObject() - .put("body", new JSONObject() - .put("documents", this.serializeDocuments(documents)) - ); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("document", "mUpdate"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #mUpdateDocument(Document[], Options, ResponseListener)} - */ - public Collection mUpdateDocument(final Document[] documents, final ResponseListener listener) throws JSONException { - return this.mUpdateDocument(documents, new Options(), listener); - } - - /** - * {@link #mUpdateDocument(Document[], Options, ResponseListener)} - */ - public Collection mUpdateDocument(final Document[] documents, Options options) throws JSONException { - return this.mUpdateDocument(documents, options, null); - } - - /** - * {@link #mUpdateDocument(Document[], Options, ResponseListener)} - */ - public Collection mUpdateDocument(final Document[] documents) throws JSONException { - return this.mUpdateDocument(documents, new Options(), null); - } - - /** - * {@link #publishMessage(Document, Options, ResponseListener)} - */ - public Collection publishMessage(final Document document) { - return this.publishMessage(document, null, null); - } - - /** - * {@link #publishMessage(Document, Options, ResponseListener)} - */ - public Collection publishMessage(final Document document, final ResponseListener listener) { - return this.publishMessage(document, null, listener); - } - - /** - * {@link #publishMessage(Document, Options, ResponseListener)} - */ - public Collection publishMessage(final Document document, final Options options) { - return this.publishMessage(document, options, null); - } - - /** - * Publish a real-time message - * - * @param document Document to publish - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection publishMessage(final Document document, final Options options, final ResponseListener listener) { - if (document == null) { - throw new IllegalArgumentException("Cannot publish a null document"); - } - - return this.publishMessage(document.getContent(), options, listener); - } - - /** - * {@link #publishMessage(JSONObject, Options, ResponseListener)} - */ - public Collection publishMessage(final JSONObject content) { - return this.publishMessage(content, null, null); - } - - /** - * {@link #publishMessage(JSONObject, Options, ResponseListener)} - */ - public Collection publishMessage(final JSONObject content, final ResponseListener listener) { - return this.publishMessage(content, null, listener); - } - - /** - * {@link #publishMessage(JSONObject, Options, ResponseListener)} - */ - public Collection publishMessage(final JSONObject content, final Options options) { - return this.publishMessage(content, options, null); - } - - /** - * Publish a real-time message - * - * @param content Message content - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection publishMessage(final JSONObject content, final Options options, final ResponseListener listener) { - if (content == null) { - throw new IllegalArgumentException("Cannot publish null content"); - } - - try { - JSONObject data = new JSONObject().put("body", content); - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("realtime", "publish"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - listener.onSuccess(response); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #replaceDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection replaceDocument(final String documentId, final JSONObject content) { - return this.replaceDocument(documentId, content, null, null); - } - - /** - * {@link #replaceDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection replaceDocument(final String documentId, final JSONObject content, final ResponseListener listener) { - return this.replaceDocument(documentId, content, null, listener); - } - - /** - * {@link #replaceDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection replaceDocument(final String documentId, final JSONObject content, final Options options) { - return this.replaceDocument(documentId, content, options, null); - } - - /** - * Replace an existing document with a new one. - * - * @param documentId Document unique identifier - * @param content New document content - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection replaceDocument(final String documentId, final JSONObject content, final Options options, final ResponseListener listener) { - if (documentId == null) { - throw new IllegalArgumentException("Collection.replaceDocument: documentId required"); - } - - try { - JSONObject data = new JSONObject().put("_id", documentId).put("body", content); - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("document", "createOrReplace"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - JSONObject result = response.getJSONObject("result"); - Document document = new Document(Collection.this, result.getString("_id"), result.getJSONObject("_source")); - document.setVersion(result.getLong("_version")); - listener.onSuccess(document); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #validateSpecifications(JSONObject, Options, ResponseListener)} - */ - public void validateSpecifications(JSONObject specifications, ResponseListener listener) throws JSONException { - this.validateSpecifications(specifications, new Options(), listener); - } - - /** - * Validates the provided specifications - * - * @param specifications Specifications content - * @param options Request options - * @param listener Response callback listener - * @throws JSONException - */ - public void validateSpecifications(JSONObject specifications, Options options, final ResponseListener listener) throws JSONException { - if (specifications == null) { - throw new IllegalArgumentException("Collection.validateSpecifications: specifications cannot be null"); - } - - if (listener == null) { - throw new IllegalArgumentException("listener cannot be null"); - } - - JSONObject data = new JSONObject() - .put("body", new JSONObject() - .put(this.getIndex(), new JSONObject() - .put(this.getCollection(), specifications) - ) - ); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("collection", "validateSpecifications"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result").getBoolean("valid")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #room(RoomOptions)} - */ - public Room room() { - return this.room(null); - } - - /** - * Room object constructor, attaching it to this - * data collection - * - * @param options Request options - * @return a newly instantiated Room object - */ - public Room room(RoomOptions options) { - return new Room(this, options); - } - - /** - * {@link #setHeaders(JSONObject, boolean)} - */ - public Collection setHeaders(final JSONObject content) { - return this.setHeaders(content, false); - } - - /** - * Sets headers global to this data collection - * - * @param content Headers content - * @param replace true: replace existing headers, false: append - * @return this - */ - public Collection setHeaders(final JSONObject content, final boolean replace) { - try { - if (content == null) { - if (replace) { - this.headers = new JSONObject(); - } - - return this; - } - - if (replace) { - this.headers = new JSONObject(content.toString()); - } else { - for (Iterator ite = content.keys(); ite.hasNext(); ) { - String key = (String) ite.next(); - this.headers.put(key, content.get(key)); - } - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #subscribe(JSONObject, RoomOptions, ResponseListener)} - */ - public SubscribeListener subscribe(final JSONObject filters, final ResponseListener listener) { - return this.subscribe(filters, null, listener); - } - - /** - * {@link #subscribe(JSONObject, RoomOptions, ResponseListener)} - */ - public SubscribeListener subscribe(final RoomOptions options, final ResponseListener listener) { - return this.subscribe(null, options, listener); - } - - /** - * Subscribes to this data collection with a set of Kuzzle DSL filters. - * - * @param filters Subscription filters - * @param options Request options - * @param listener Response callback listener - * @return an object with a onDone() callback triggered when the subscription is active - */ - public SubscribeListener subscribe(final JSONObject filters, final RoomOptions options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Collection.subscribe: listener required"); - } - this.kuzzle.isValid(); - final Room room = new Room(this, options); - final SubscribeListener subscribeResponseListener = new SubscribeListener(); - - room.renew(filters, listener, subscribeResponseListener); - - return subscribeResponseListener; - } - - /** - * {@link #truncate(Options, ResponseListener)} - */ - public Collection truncate() { - return this.truncate(null, null); - } - - /** - * {@link #truncate(Options, ResponseListener)} - */ - public Collection truncate(final Options options) { - return this.truncate(options, null); - } - - /** - * {@link #truncate(Options, ResponseListener)} - */ - public Collection truncate(final ResponseListener listener) { - return this.truncate(null, listener); - } - - /** - * Truncate the data collection, removing all stored documents but keeping all associated mappings. - * - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection truncate(final Options options, final ResponseListener listener) { - JSONObject data = new JSONObject(); - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("collection", "truncate"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #updateDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection updateDocument(final String documentId, final JSONObject content) { - return this.updateDocument(documentId, content, null, null); - } - - /** - * {@link #updateDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection updateDocument(final String documentId, final JSONObject content, final Options options) { - return this.updateDocument(documentId, content, options, null); - } - - /** - * {@link #updateDocument(String, JSONObject, Options, ResponseListener)} - */ - public Collection updateDocument(final String documentId, final JSONObject content, final ResponseListener listener) { - return this.updateDocument(documentId, content, null, listener); - } - - /** - * Update parts of a document - * - * @param documentId Document unique identifier - * @param content Document content to update - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection updateDocument(final String documentId, final JSONObject content, final Options options, final ResponseListener listener) { - if (documentId == null) { - throw new IllegalArgumentException("Collection.updateDocument: documentId required"); - } - if (content == null) { - throw new IllegalArgumentException("Collection.updateDocument: content required"); - } - - try { - JSONObject data = new JSONObject().put("_id", documentId).put("body", content); - this.kuzzle.addHeaders(data, this.getHeaders()); - - if (options != null && options.getRetryOnConflict() > 0) { - data.put("retryOnConflict", options.getRetryOnConflict()); - } - - this.kuzzle.query(makeQueryArgs("document", "update"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - JSONObject result = response.getJSONObject("result"); - Document document = new Document(Collection.this, result.getString("_id"), result.getJSONObject("_source")); - document.setVersion(result.getLong("_version")); - document.refresh(listener); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #updateSpecifications(JSONObject, Options, ResponseListener)} - */ - public Collection updateSpecifications(final JSONObject specifications) throws JSONException { - return this.updateSpecifications(specifications, new Options(), null); - } - - /** - * {@link #updateSpecifications(JSONObject, Options, ResponseListener)} - */ - public Collection updateSpecifications(final JSONObject specifications, final Options options) throws JSONException { - return this.updateSpecifications(specifications, options, null); - } - - /** - * {@link #updateSpecifications(JSONObject, Options, ResponseListener)} - */ - public Collection updateSpecifications(final JSONObject specifications, final ResponseListener listener) throws JSONException { - return this.updateSpecifications(specifications, new Options(), listener); - } - - /** - * Updates the current specifications of this collection - * - * @param specifications Updated specifications content - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Collection updateSpecifications(final JSONObject specifications, final Options options, final ResponseListener listener) throws JSONException { - if (specifications == null) { - throw new IllegalArgumentException("Collection.updateSpecifications: specifications cannot be null"); - } - - JSONObject data = new JSONObject() - .put("body", new JSONObject() - .put(this.getIndex(), new JSONObject() - .put(this.getCollection(), specifications) - ) - ); - - try { - this.kuzzle.addHeaders(data, this.getHeaders()); - this.kuzzle.query(makeQueryArgs("collection", "updateSpecifications"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * Get the attached Kuzzle object instance. - * - * @return attached Kuzzle object instance - */ - public Kuzzle getKuzzle() { - return kuzzle; - } - - /** - * Get this data collection name - * - * @return data collection name - */ - public String getCollection() { - return collection; - } - - /** - * Get the parent data index name - * - * @return parent data index name - */ - public String getIndex() { - return this.index; - } - - /** - * Get the data collection global headers - * - * @return data collection global headers - */ - public JSONObject getHeaders() { - return this.headers; - } -} diff --git a/src/main/java/io/kuzzle/sdk/core/CollectionMapping.java b/src/main/java/io/kuzzle/sdk/core/CollectionMapping.java deleted file mode 100644 index ab599ef5..00000000 --- a/src/main/java/io/kuzzle/sdk/core/CollectionMapping.java +++ /dev/null @@ -1,246 +0,0 @@ -package io.kuzzle.sdk.core; - - - -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.Iterator; - -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -public class CollectionMapping { - - private JSONObject headers; - private JSONObject mapping; - private Kuzzle kuzzle; - private String collection; - private Collection dataCollection; - - /** - * Constructor - * - * @param kuzzleDataCollection - Parent data collection - */ - public CollectionMapping(final Collection kuzzleDataCollection) { - this(kuzzleDataCollection, null); - } - - /** - * Constructor - * - * @param kuzzleDataCollection - Parent data collection - * @param mapping - Mapping content - */ - public CollectionMapping(final Collection kuzzleDataCollection, final JSONObject mapping) { - try { - this.headers = new JSONObject(kuzzleDataCollection.getHeaders().toString()); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - - this.kuzzle = kuzzleDataCollection.getKuzzle(); - this.collection = kuzzleDataCollection.getCollection(); - this.mapping = mapping == null ? new JSONObject() : mapping; - this.dataCollection = kuzzleDataCollection; - } - - /** - * Copy constructor - * - * @param kuzzleDataMapping - The CollectionMapping object to copy - */ - public CollectionMapping(final CollectionMapping kuzzleDataMapping) { - this(kuzzleDataMapping.dataCollection, kuzzleDataMapping.mapping); - } - - /** - * {@link #apply(Options, ResponseListener)} - */ - public CollectionMapping apply() { - return this.apply(null, null); - } - - /** - * {@link #apply(Options, ResponseListener)} - */ - public CollectionMapping apply(final Options options) { - return this.apply(options, null); - } - - /** - * {@link #apply(Options, ResponseListener)} - */ - public CollectionMapping apply(final ResponseListener listener) { - return this.apply(null, listener); - } - - /** - * Applies this mapping content to the data collection. - * - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public CollectionMapping apply(final Options options, final ResponseListener listener) { - JSONObject data = new JSONObject(); - JSONObject properties = new JSONObject(); - try { - properties.put("properties", this.mapping); - data.put("body", properties); - this.kuzzle.addHeaders(data, this.headers); - this.kuzzle.query(this.dataCollection.makeQueryArgs("collection", "updateMapping"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - listener.onSuccess(CollectionMapping.this); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #refresh(Options, ResponseListener)} - */ - public void refresh(final ResponseListener listener) { - refresh(null, listener); - } - - /** - * Gets a refreshed copy of the current object - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void refresh(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("CollectionMapping.refresh: listener callback missing"); - } - - JSONObject data = new JSONObject(); - try { - this.kuzzle.addHeaders(data, this.headers); - this.kuzzle.query(this.dataCollection.makeQueryArgs("collection", "getMapping"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject args) { - try { - CollectionMapping newMapping = new CollectionMapping(CollectionMapping.this.dataCollection); - JSONObject mappings = args.getJSONObject(CollectionMapping.this.dataCollection.getIndex()).getJSONObject("mappings"); - newMapping.mapping = mappings.getJSONObject(CollectionMapping.this.collection); - - listener.onSuccess(newMapping); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject object) { - listener.onError(object); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * Remove a field from this mapping - * Changes made by this function won't be applied until you call the apply method - * - * @param field - Field name to remove - * @return this - */ - public CollectionMapping remove(final String field) { - if (this.mapping.has(field)) { - CollectionMapping.this.mapping.remove(field); - } - - return this; - } - - /** - * Attach a mapping to a field - * - * @param field - Field name - * @param mapping - Field mapping - * @return this - * @throws JSONException - */ - public CollectionMapping set(final String field, final JSONObject mapping) throws JSONException { - this.mapping.put(field, mapping); - return this; - } - - /** - * Get the global headers for this object - * - * @return global headers for this object - */ - public JSONObject getHeaders() { - return headers; - } - - /** - * {@link #setHeaders(JSONObject, boolean)} - */ - public CollectionMapping setHeaders(final JSONObject content) { - return this.setHeaders(content, false); - } - - /** - * Helper function allowing to set headers while chaining calls. - * If the replace argument is set to true, replace the current headers with the provided content. - * Otherwise, it appends the content to the current headers, only replacing already existing values - * - * @param content - Headers to append or replace - * @param replace - false (default): append the content, true: replace the current headers - * @return this - */ - public CollectionMapping setHeaders(final JSONObject content, final boolean replace) { - try { - if (content == null) { - if (replace) { - this.headers = new JSONObject(); - } - - return this; - } - - if (replace) { - this.headers = new JSONObject(content.toString()); - } else { - for (Iterator ite = content.keys(); ite.hasNext(); ) { - String key = (String) ite.next(); - this.headers.put(key, content.get(key)); - } - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * Get this mapping raw content - * - * @return mapping raw content - */ - public JSONObject getMapping() { - return mapping; - } -} diff --git a/src/main/java/io/kuzzle/sdk/core/Document.java b/src/main/java/io/kuzzle/sdk/core/Document.java deleted file mode 100644 index 021dc3c1..00000000 --- a/src/main/java/io/kuzzle/sdk/core/Document.java +++ /dev/null @@ -1,628 +0,0 @@ -package io.kuzzle.sdk.core; - - - -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.Iterator; - -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.SubscribeListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.NotificationResponse; - -public class Document { - private final Collection dataCollection; - private final String collection; - private final Kuzzle kuzzle; - private JSONObject headers; - - private String id; - private JSONObject content; - private JSONObject meta; - private long version = -1; - - /** - * Kuzzle handles documents either as real-time messages or as stored documents. - * Document is the object representation of one of these documents. - * - * @param kuzzleDataCollection - An instantiated Collection object - * @param id - Unique document identifier - * @param content - The content of the document - * @param meta - Document metadata - * @throws JSONException - */ - public Document(final Collection kuzzleDataCollection, final String id, final JSONObject content, final JSONObject meta) throws JSONException { - if (kuzzleDataCollection == null) { - throw new IllegalArgumentException("Document: Collection argument missing"); - } - - this.dataCollection = kuzzleDataCollection; - this.collection = kuzzleDataCollection.getCollection(); - this.kuzzle = kuzzleDataCollection.getKuzzle(); - this.setId(id); - this.setContent(content, true); - - if (meta != null) { - this.meta = new JSONObject(meta.toString()); - } - - this.headers = kuzzleDataCollection.getHeaders(); - } - - /** - * Kuzzle handles documents either as real-time messages or as stored documents. - * Document is the object representation of one of these documents. - * - * @param kuzzleDataCollection - An instantiated Collection object - * @param id - Unique document identifier - * @param content - The content of the document - * @throws JSONException - */ - public Document(final Collection kuzzleDataCollection, final String id, final JSONObject content) throws JSONException { - this(kuzzleDataCollection, id, content, null); - } - - /** - * Kuzzle handles documents either as real-time messages or as stored documents. - * Document is the object representation of one of these documents. - * - * @param kuzzleDataCollection - An instantiated Collection object - * @throws JSONException - */ - public Document(final Collection kuzzleDataCollection) throws JSONException { - this(kuzzleDataCollection, null, null, null); - } - - - /** - * Kuzzle handles documents either as real-time messages or as stored documents. - * Document is the object representation of one of these documents. - * - * @param kuzzleDataCollection - An instantiated Collection object - * @param id - Unique document identifier - * @throws JSONException - */ - public Document(final Collection kuzzleDataCollection, final String id) throws JSONException { - this(kuzzleDataCollection, id, null, null); - } - - /** - * Kuzzle handles documents either as real-time messages or as stored documents. - * Document is the object representation of one of these documents. - * - * @param kuzzleDataCollection - An instantiated Collection object - * @param content - The content of the document - * @throws JSONException - */ - public Document(final Collection kuzzleDataCollection, final JSONObject content) throws JSONException { - this(kuzzleDataCollection, null, content, null); - } - - /** - * Kuzzle handles documents either as real-time messages or as stored documents. - * Document is the object representation of one of these documents. - * - * @param kuzzleDataCollection - An instantiated Collection object - * @param content - The content of the document - * @param meta - Document metadata - * @throws JSONException - */ - public Document(final Collection kuzzleDataCollection, final JSONObject content, final JSONObject meta) throws JSONException { - this(kuzzleDataCollection, null, content, meta); - } - - /** - * {@link #delete(Options, ResponseListener)} - */ - public void delete(final Options options) { - this.delete(options, null); - } - - /** - * {@link #delete(Options, ResponseListener)} - */ - public void delete(final ResponseListener listener) { - this.delete(null, listener); - } - - /** - * {@link #delete(Options, ResponseListener)} - */ - public void delete() { - this.delete(null, null); - } - - /** - * Delete this document from Kuzzle - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void delete(final Options options, final ResponseListener listener) { - try { - if (this.id == null) { - throw new IllegalStateException("Document.delete: cannot delete a document without a document ID"); - } - - this.kuzzle.query(this.dataCollection.makeQueryArgs("document", "delete"), this.serialize(), options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - setId(null); - if (listener != null) { - try { - listener.onSuccess(object.getString("result")); - } catch (JSONException e) { - e.printStackTrace(); - }; - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #exists(Options, ResponseListener)} - */ - public void exists(final ResponseListener listener) { - this.exists(null, listener); - } - - /** - * Ask Kuzzle if this document exists - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void exists(final Options options, final ResponseListener listener) { - if (this.id == null) { - throw new IllegalStateException("Document.exists: cannot check if the document exists if no id has been provided"); - } - - if (listener == null) { - throw new IllegalArgumentException("Document.exists: a valid ResponseListener object is required"); - } - - try { - this.kuzzle.query(this.dataCollection.makeQueryArgs("document", "exists"), this.serialize(), options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - try { - listener.onSuccess(object.getBoolean("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #refresh(Options, ResponseListener)} - */ - public void refresh(final ResponseListener listener) { - this.refresh(null, listener); - } - - /** - * Gets a refreshed copy of this document from Kuzzle - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void refresh(final Options options, final ResponseListener listener) { - if (this.id == null) { - throw new IllegalStateException("Document.refresh: cannot retrieve a document if no id has been provided"); - } - - if (listener == null) { - throw new IllegalArgumentException("Document.refresh: a valid ResponseListener object is required"); - } - - try { - JSONObject content = new JSONObject(); - content.put("_id", this.getId()); - - this.kuzzle.query(this.dataCollection.makeQueryArgs("document", "get"), content, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject args) { - try { - JSONObject result = args.getJSONObject("result"); - Document newDocument = new Document( - Document.this.dataCollection, - result.getString("_id"), - result.getJSONObject("_source"), - result.getJSONObject("_meta") - ); - - newDocument.setVersion(result.getLong("_version")); - listener.onSuccess(newDocument); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject arg) { - listener.onError(arg); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Document save() { - return save(null, null); - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Document save(final Options options) { - return this.save(options, null); - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Document save(final ResponseListener listener) { - return save(null, listener); - } - - /** - * Saves this document into Kuzzle. - * If this is a new document, this function will create it in Kuzzle and the id property will be made available. - * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content of this object. - * - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Document save(final Options options, final ResponseListener listener) { - try { - kuzzle.query(this.dataCollection.makeQueryArgs("document", "createOrReplace"), this.serialize(), options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - Document.this.setId(result.getString("_id")); - Document.this.setVersion(result.getLong("_version")); - - if (listener != null) { - listener.onSuccess(Document.this); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #publish(Options)} - */ - public Document publish() { - return this.publish(null); - } - - /** - * Sends the content of this document as a real-time message. - * - * @param options - Request options - * @return this - */ - public Document publish(final Options options) { - try { - kuzzle.query(this.dataCollection.makeQueryArgs("realtime", "publish"), this.serialize(), options, null); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #setContent(JSONObject, boolean)} - */ - public Document setContent(final JSONObject content) throws JSONException { - this.setContent(content, false); - return this; - } - - /** - * Sets this document content - * - * @param content - New content for this document - * @param replace - true: replace the current content, false (default): update/append it - * @return this - * @throws JSONException - */ - public Document setContent(final JSONObject content, final boolean replace) throws JSONException { - if (replace) { - if (content != null) { - this.content = new JSONObject(content.toString()); - } - else { - this.content = new JSONObject(); - } - } else if (content != null) { - for (Iterator iterator = content.keys(); iterator.hasNext(); ) { - String key = (String) iterator.next(); - this.content.put(key, content.get(key)); - } - } - - if (this.content.has("version")) { - Object version = this.content.get("version"); - if (version instanceof Long || version instanceof Integer) { - this.version = this.content.getLong("version"); - this.content.remove("version"); - } - } - - return this; - } - - /** - * Set a document field value - * - * @param key - Field name to set - * @param value - New field value - * @return this - * @throws JSONException - */ - public Document setContent(final String key, final Object value) throws JSONException { - if (key == null) { - throw new IllegalArgumentException("Document.setContent: key required"); - } - - this.content.put(key, value); - return this; - } - - /** - * {@link #subscribe(RoomOptions, ResponseListener)} - */ - public SubscribeListener subscribe(final ResponseListener listener) { - return this.subscribe(null, listener); - } - - /** - * Subscribe to changes occuring on this document. - * Throws an error if this document has not yet been created in Kuzzle. - * - * @param options - Room object constructor options - * @param listener - Response callback listener - * @return an object with a "onDone" callback triggered when the subscription is active - */ - public SubscribeListener subscribe(final RoomOptions options, final ResponseListener listener) { - if (this.id == null) { - throw new IllegalStateException("Document.subscribe: cannot subscribe to a document if no ID has been provided"); - } - - SubscribeListener returnValue; - - try { - JSONObject filters = new JSONObject("{" + - "\"ids\": {" + - "\"values\": [\"" + this.id + "\"]" + - "}" + - "}"); - returnValue = this.dataCollection.subscribe(filters, options, listener); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return returnValue; - } - - /** - * Get the parent data collection name - * - * @return parent data collection name - */ - public String getCollection() { - return collection; - } - - /** - * Document content getter - * - * @return current document content - */ - public JSONObject getContent() { - return this.content; - } - - - /** - * Get document content field - * - * @param key - Field name to get - * @return field value - * @throws JSONException - */ - public Object getContent(final String key) throws JSONException { - if (this.content.has(key)) { - return this.content.get(key); - } - - return null; - } - - /** - * Document metadata getter - * - * @return this document metadata - */ - public JSONObject getMeta() { - return this.meta; - } - - - /** - * Get a metadata field value - * - * @param key - Metadata field name to get - * @return metadata field value - * @throws JSONException - */ - public Object getMeta(final String key) throws JSONException { - if (this.meta.has(key)) { - return this.meta.get(key); - } - - return null; - } - - /** - * {@link #setHeaders(JSONObject, boolean)} - */ - public Document setHeaders(final JSONObject content) { - return this.setHeaders(content, false); - } - - /** - * Replace or append/update global headers for this object - * - * @param content - new headers content - * @param replace - true: replace the current headers, false (default): append/update - * @return this - */ - public Document setHeaders(final JSONObject content, final boolean replace) { - try { - if (content == null) { - if (replace) { - this.content = new JSONObject(); - } - - return this; - } - - if (replace) { - this.headers = new JSONObject(content.toString()); - } else { - for (Iterator ite = content.keys(); ite.hasNext(); ) { - String key = (String) ite.next(); - this.headers.put(key, content.get(key)); - } - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * Get the global headers for this object - * - * @return global headers for this object - */ - public JSONObject getHeaders() { - return this.headers; - } - - /** - * Unique identifier getter - * - * @return this document unique identifier - */ - public String getId() { - return this.id; - } - - /** - * Set this document unique identifier - * - * @param id - New document unique identifier - * @return this - */ - public Document setId(final String id) { - this.id = id; - return this; - } - - /** - * Get this document version - * - * @return this document version - */ - public long getVersion() { - return this.version; - } - - /** - * Serializes this document into a plain old JSON object - * - * @return JSON object representing this document - */ - public JSONObject serialize() { - JSONObject data = new JSONObject(); - - try { - if (this.id != null) { - data.put("_id", this.getId()); - } - - if (this.version != -1) { - data.put("_version", this.version); - } - - data.put("body", this.getContent()); - this.kuzzle.addHeaders(data, getHeaders()); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - - return data; - } - - public String toString() { - return this.serialize().toString(); - } - - /** - * Set this document version - * - * @param version - New document version - * @return this - */ - public Document setVersion(long version) { - if (version > 0) { - this.version = version; - } - - return this; - } -} diff --git a/src/main/java/io/kuzzle/sdk/core/Kuzzle.java b/src/main/java/io/kuzzle/sdk/core/Kuzzle.java deleted file mode 100644 index 277db6ab..00000000 --- a/src/main/java/io/kuzzle/sdk/core/Kuzzle.java +++ /dev/null @@ -1,2785 +0,0 @@ -package io.kuzzle.sdk.core; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Calendar; -import java.util.Date; -import java.util.Iterator; -import java.util.Map; -import java.util.Queue; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.EventListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.TokenValidity; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.security.User; -import io.kuzzle.sdk.state.KuzzleQueue; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.EventList; -import io.kuzzle.sdk.util.OfflineQueueLoader; -import io.kuzzle.sdk.util.QueryObject; -import io.kuzzle.sdk.util.QueueFilter; -import tech.gusavila92.websocketclient.WebSocketClient; - -/** - * The type Kuzzle. - */ -public class Kuzzle { - private final int MAX_EMIT_TIMEOUT = 10; - private final int EVENT_TIMEOUT = 200; - - protected ConcurrentHashMap eventListeners = new ConcurrentHashMap<>(); - - protected WebSocketClient socket; - protected ConcurrentHashMap currentQueries = new ConcurrentHashMap<>(); - protected ConcurrentHashMap roomList = new ConcurrentHashMap<>(); - - protected Map> collections = new ConcurrentHashMap<>(); - protected boolean autoReconnect = true; - protected JSONObject headers = new JSONObject(); - protected JSONObject _volatile; - protected String host; - protected Integer port; - protected boolean isSsl; - protected ResponseListener connectionCallback; - protected States state = States.INITIALIZING; - protected long reconnectionDelay; - protected boolean autoResubscribe; - protected boolean autoQueue; - protected boolean autoReplay; - - protected QueueFilter queueFilter = new QueueFilter() { - @Override - public boolean filter(JSONObject object) { - return true; - } - }; - - protected long replayInterval; - protected boolean queuing = false; - protected String defaultIndex; - protected ConcurrentHashMap requestHistory = new ConcurrentHashMap<>(); - protected KuzzleQueue offlineQueue = new KuzzleQueue<>(); - protected int queueTTL; - protected int queueMaxSize; - protected String jwtToken = null; - - /* - This property contains the centralized subscription list in the following format: - roomId: - kuzzleRoomID_1: kuzzleRoomInstance_1, - kuzzleRoomID_2: kuzzleRoomInstance_2, - ... - pending: // pending subscriptions - kuzzleRoomID_x: kuzzleRoomInstance_x, - ... - - This was made to allow multiple subscriptions on the same set of filters, - something that Kuzzle does not permit. - This structure also allows renewing subscriptions after a connection loss - */ - protected ConcurrentHashMap> subscriptions = new ConcurrentHashMap<>(); - - private OfflineQueueLoader offlineQueueLoader; - - /** - * Security static class - */ - public Security security; - - private ResponseListener loginCallback; - - public MemoryStorage memoryStorage; - - public static class QueryArgs { - public String controller; - public String action; - public String index; - public String collection; - } - - /** - * Emit an event to all registered listeners - * An event cannot be emitted multiple times before a timeout has been reached. - * - * @param event - Event name to emit - * @param args - Event payload - */ - protected void emitEvent(Event event, Object... args) { - long now = System.currentTimeMillis(); - - if (this.eventListeners.containsKey(event)) { - EventList l = this.eventListeners.get(event); - - if (l.lastEmitted < now - this.EVENT_TIMEOUT) { - for (io.kuzzle.sdk.util.Event e : l.values()) { - e.trigger(args); - } - - l.lastEmitted = now; - } - } - } - - /** - * Connection status getter - * @return Connection status - */ - public States getState() { - return state; - } - - /** - * Constructor - * - * @param host - Target host name or IP address - * @param options - Request options - * @param connectionCallback - On success callback listener - * @throws URISyntaxException - */ - public Kuzzle(final String host, final Options options, final ResponseListener connectionCallback) throws URISyntaxException { - if (host == null || host.isEmpty()) { - throw new IllegalArgumentException("Host name/address can't be empty"); - } - - this.host = host; - - Options opt = (options != null ? options : new Options()); - - this.autoQueue = opt.isAutoQueue(); - this.autoReconnect = opt.isAutoReconnect(); - this.autoReplay = opt.isAutoReplay(); - this.autoResubscribe = opt.isAutoResubscribe(); - this.defaultIndex = opt.getDefaultIndex(); - this.headers = opt.getHeaders(); - this._volatile = opt.getVolatile(); - this.port = opt.getPort(); - this.isSsl = opt.isSsl(); - this.queueMaxSize = opt.getQueueMaxSize(); - this.queueTTL = opt.getQueueTTL(); - this.reconnectionDelay = opt.getReconnectionDelay(); - this.replayInterval = opt.getReplayInterval(); - - this.connectionCallback = connectionCallback; - - if (opt.getOfflineMode() == Mode.AUTO) { - this.autoReconnect = this.autoQueue = this.autoReplay = this.autoResubscribe = true; - } - if (opt.getConnect() == Mode.AUTO) { - connect(); - } else { - this.state = States.READY; - } - - this.security = new Security(this); - this.memoryStorage = new MemoryStorage(this); - this.subscriptions.put("pending", new ConcurrentHashMap()); - } - - /** - * Constructor - * - * @param host - Target Kuzzle host name or IP address - * @throws URISyntaxException - */ - public Kuzzle(final String host) throws URISyntaxException { - this(host, null, null); - } - - /** - * Constructor - * - * @param host - Target Kuzzle host name or IP address - * @param cb - On success connection callback listener - * @throws URISyntaxException - */ - public Kuzzle(final String host, final ResponseListener cb) throws URISyntaxException { - this(host, null, cb); - } - - /** - * Constructor - * - * @param host - Target Kuzzle host name or IP address - * @param options - Request options - * @throws URISyntaxException - */ - public Kuzzle(final String host, Options options) throws URISyntaxException { - this(host, options, null); - } - - /** - * Adds a listener to a Kuzzle global event. When an event is triggered, - * listeners are called in the order of their insertion. - * - * @param kuzzleEvent - Name of the global event to subscribe to - * @param listener - Response callback listener - * @return this - */ - public Kuzzle addListener(final Event kuzzleEvent, final EventListener listener) { - this.isValid(); - - io.kuzzle.sdk.util.Event e = new io.kuzzle.sdk.util.Event(kuzzleEvent) { - @Override - public void trigger(Object... args) { - listener.trigger(args); - } - }; - - if (!eventListeners.containsKey(kuzzleEvent)) { - eventListeners.put(kuzzleEvent, new EventList()); - } - - eventListeners.get(kuzzleEvent).put(listener, e); - return this; - } - - /** - * Check an authentication token validity - * - * @param token - Token to check (JWT) - * @param listener - Response callback listener - */ - public void checkToken(final String token, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.checkToken: listener required"); - } - - if (token == null || token.isEmpty()) { - throw new IllegalArgumentException("Kuzzle.checkToken: token required"); - } - - try { - QueryArgs args = new QueryArgs(); - args.controller = "auth"; - args.action = "checkToken"; - JSONObject request = new JSONObject(); - request.put("body", new JSONObject().put("token", token)); - this.query(args, request, new Options().setQueuable(false), new OnQueryDoneListener() { - - @Override - public void onSuccess(JSONObject response) { - try { - TokenValidity validity = new TokenValidity(); - JSONObject result = response.getJSONObject("result"); - validity.setValid(result.getBoolean("valid")); - if (validity.isValid()) { - validity.setExpiresAt(new Date(result.getLong("expiresAt"))); - } else { - validity.setState(result.getString("state")); - } - listener.onSuccess(validity); - } catch (JSONException e) { - throw new RuntimeException(); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * Connects to a Kuzzle instance using the provided host and port. - * - * @return this - * @throws URISyntaxException - */ - public Kuzzle connect() throws URISyntaxException { - if (!this.isValidState()) { - if (connectionCallback != null) { - connectionCallback.onSuccess(null); - return this; - } - } - - if (this.socket != null) { - this.disconnect(); - } - - this.socket = createSocket(); - - Kuzzle.this.state = States.CONNECTING; - - if (socket != null) { - socket.connect(); - } - - return this; - } - - /** - * Collection object factory. Default index must be set. - * - * @param collection - Data collection name - * @return Instantiated Collection object - */ - public Collection collection(final String collection) { - this.isValid(); - if (this.defaultIndex == null) { - throw new IllegalArgumentException("Collection: unable to create a new data collection object: no index specified"); - } - - return this.collection(collection, this.defaultIndex); - } - - /** - * Collection object factory - * - * @param collection - Data collection name - * @param index - Parent data index name - * @return Instantiated Collection object - */ - public Collection collection(final String collection, final String index) { - this.isValid(); - if (index == null && this.defaultIndex == null) { - throw new IllegalArgumentException("Collection: unable to create a new data collection object: no index specified"); - } - - if (!this.collections.containsKey(collection)) { - Map col = new ConcurrentHashMap<>(); - col.put(collection, new Collection(this, collection, index)); - this.collections.put(index, col); - } - return this.collections.get(index).get(collection); - } - - /** - * {@link #createIndex(String, Options, ResponseListener)} - */ - public Kuzzle createIndex(final String index, final ResponseListener cb) { - return createIndex(index, null, cb); - } - - /** - * {@link #createIndex(String, Options, ResponseListener)} - */ - public Kuzzle createIndex(final String index) { - return createIndex(index, null, null); - } - - /** - * Create a new data index - * - * @param index - index name to create - * @param options - Request options - * @param cb - Response callback listener - * @return this - */ - public Kuzzle createIndex(final String index, final Options options, final ResponseListener cb) { - if (index == null && defaultIndex == null) { - throw new IllegalArgumentException("Collection.createIndex: index required"); - } - - QueryArgs args = new QueryArgs(); - args.controller = "index"; - args.action = "create"; - - JSONObject request = new JSONObject(); - try { - request.put("index", index == null ? defaultIndex : index); - this.query(args, request, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - cb.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - cb.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * Empties the offline queue without replaying it. - * - * @return this - */ - public Kuzzle flushQueue() { - this.getOfflineQueue().clear(); - return this; - } - - /** - * {@link #getAllStatistics(Options, ResponseListener)} - */ - public void getAllStatistics(final ResponseListener listener) { - this.getAllStatistics(null, listener); - } - - /** - * Get all Kuzzle usage statistics frames - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void getAllStatistics(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.getAllStatistics: listener required"); - } - - this.isValid(); - try { - QueryArgs args = new QueryArgs(); - args.controller = "server"; - args.action = "getAllStats"; - this.query(args, null, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - try { - JSONArray hits = object.getJSONObject("result").getJSONArray("hits"); - JSONObject[] frames = new JSONObject[hits.length()]; - - for(int i = 0; i < hits.length(); i++) { - frames[i] = hits.getJSONObject(i); - } - - listener.onSuccess(frames); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #getStatistics(Options, ResponseListener)} - */ - public void getStatistics(final ResponseListener listener) { - this.getStatistics(null, listener); - } - - /** - * Get Kuzzle usage statistics - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void getStatistics(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.getStatistics: listener required"); - } - this.isValid(); - JSONObject body = new JSONObject(); - JSONObject data = new JSONObject(); - - try { - body.put("body", data); - QueryArgs args = new QueryArgs(); - args.controller = "server"; - args.action = "getLastStats"; - this.query(args, body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(new JSONObject[]{response.getJSONObject("result")}); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #getStatistics(long, Options, ResponseListener)} - */ - public void getStatistics(long timestamp, final ResponseListener listener) { - this.getStatistics(timestamp, null, listener); - } - - /** - * Get Kuzzle usage statistics starting from a provided timestamp - * - * @param timestamp - Statistic starting time to retrieve - * @param options - Request options - * @param listener - Response callback listener - */ - public void getStatistics(long timestamp, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.getStatistics: listener required"); - } - - this.isValid(); - JSONObject body = new JSONObject(); - JSONObject data = new JSONObject(); - - try { - data.put("since", timestamp); - body.put("body", data); - QueryArgs args = new QueryArgs(); - args.controller = "server"; - args.action = "getStats"; - this.query(args, body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONArray hits = response.getJSONObject("result").getJSONArray("hits"); - JSONObject[] stats = new JSONObject[hits.length()]; - - for (int i = 0; i < hits.length(); i++) { - stats[i] = hits.getJSONObject(i); - } - - listener.onSuccess(stats); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #getServerInfo(Options, ResponseListener)} - */ - public void getServerInfo(final ResponseListener listener) { - this.getServerInfo(null, listener); - } - - /** - * Gets server info. - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void getServerInfo(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.getServerInfo: listener required"); - } - QueryArgs args = new QueryArgs(); - args.controller = "server"; - args.action = "info"; - try { - this.query(args, null, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result").getJSONObject("serverInfo")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #listCollections(Options, ResponseListener)} - */ - public void listCollections(final ResponseListener listener) { - this.listCollections(null, null, listener); - } - - /** - * {@link #listCollections(String, Options, ResponseListener)} - */ - public void listCollections(String index, final ResponseListener listener) { - this.listCollections(index, null, listener); - } - - /** - * List data collections on the default data index - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void listCollections(Options options, final ResponseListener listener) { - this.listCollections(null, options, listener); - } - - /** - * List data collections - * - * @param index - Parent data index name - * @param options - Request options - * @param listener - Response callback listener - */ - public void listCollections(String index, Options options, final ResponseListener listener) { - if (index == null) { - if (this.defaultIndex == null) { - throw new IllegalArgumentException("Kuzzle.listCollections: index required"); - } else { - index = this.defaultIndex; - } - } - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.listCollections: listener required"); - } - try { - QueryArgs args = new QueryArgs(); - args.controller = "collection"; - args.action = "list"; - args.index = index; - JSONObject query = new JSONObject(); - if (options == null) { - options = new Options(); - } - JSONObject body = new JSONObject().put("type", options.getCollectionType()); - query.put("body", body); - this.query(args, query, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject collections) { - try { - JSONArray result = collections.getJSONObject("result").getJSONArray("collections"); - JSONObject[] cols = new JSONObject[result.length()]; - - for (int i = 0; i < result.length(); i++) { - cols[i] = result.getJSONObject(i); - } - - listener.onSuccess(cols); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #listIndexes(Options, ResponseListener)} - */ - public void listIndexes(final ResponseListener listener) { - this.listIndexes(null, listener); - } - - /** - * List data indexes - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void listIndexes(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.listIndexes: listener required"); - } - QueryArgs args = new QueryArgs(); - args.controller = "index"; - args.action = "list"; - try { - this.query(args, null, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONArray array = response.getJSONObject("result").getJSONArray("indexes"); - int length = array.length(); - String[] indexes = new String[length]; - for (int i = 0; i < length; i++) { - indexes[i] = array.getString(i); - } - listener.onSuccess(indexes); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #login(String, JSONObject, int, ResponseListener)} - */ - public void login(final String strategy) { - this.login(strategy, null, -1, null); - } - - /** - * {@link #login(String, JSONObject, int, ResponseListener)} - */ - public void login(final String strategy, final JSONObject credentials) { - this.login(strategy, credentials, -1, null); - } - - /** - * {@link #login(String, JSONObject, int, ResponseListener)} - */ - public void login(final String strategy, final int expiresIn) { - this.login(strategy, null, expiresIn, null); - } - - /** - * {@link #login(String, JSONObject, int, ResponseListener)} - */ - public void login(final String strategy, final JSONObject credentials, final int expiresIn) { - this.login(strategy, credentials, expiresIn, null); - } - - /** - * {@link #login(String, JSONObject, int, ResponseListener)} - */ - public void login(final String strategy, final JSONObject credentials, final ResponseListener listener) { - this.login(strategy, credentials, -1, listener); - } - - /** - * {@link #login(String, JSONObject, int, ResponseListener)} - */ - public void login(final String strategy, final ResponseListener listener) { - this.login(strategy, null, -1, listener); - } - - /** - * {@link #login(String, JSONObject, int, ResponseListener)} - */ - public void login(final String strategy, final int expiresIn, final ResponseListener listener) { - this.login(strategy, null, expiresIn, listener); - } - - /** - * Log- Strategy name to use for the authentication - * - * @param strategy - Strategy name to use for the authentication - * @param credentials - Login credentials - * @param expiresIn - Token expiration delay - * @param listener - Response callback listener - */ - public void login(final String strategy, final JSONObject credentials, int expiresIn, final ResponseListener listener) { - if (strategy == null) { - throw new IllegalArgumentException("Kuzzle.login: cannot authenticate to Kuzzle without an authentication strategy"); - } - - this.loginCallback = listener; - - try { - Options options = new Options(); - JSONObject query = new JSONObject(); - JSONObject body = new JSONObject(); - if (credentials != null) { - body = credentials; - } - - if (expiresIn >= 0) { - query.put("expiresIn", expiresIn); - } - - query.put("strategy", strategy); - - query.put("body", body); - QueryArgs args = new QueryArgs(); - args.controller = "auth"; - args.action = "login"; - options.setQueuable(false); - - this.query(args, query, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - try { - JSONObject result = object.getJSONObject("result"); - - if (result.has("jwt")) { - Kuzzle.this.setJwtToken(result.getString("jwt")); - } - - if (listener != null) { - listener.onSuccess(result); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - try { - emitEvent(Event.loginAttempt, new JSONObject() - .put("success", false) - .put("error", error)); - } catch (JSONException e) { - throw new RuntimeException(e); - } - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * Disconnect from Kuzzle and invalidate this instance. - * Does not fire a disconnected event. - */ - public void disconnect() { - if (this.socket != null) { - this.socket.close(); - } - - this.socket = null; - this.collections.clear(); - this.state = States.DISCONNECTED; - } - - /** - * {@link #logout(ResponseListener)} - */ - public Kuzzle logout() { - return this.logout(null); - } - - /** - * Logout method - * - * @param listener - Response callback listener - * @return this - */ - public Kuzzle logout(final ResponseListener listener) { - Options options = new Options(); - - options.setQueuable(false); - - try { - QueryArgs args = new QueryArgs(); - args.controller = "auth"; - args.action = "logout"; - - this.query(args, new JSONObject(), options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - if (listener != null) { - listener.onSuccess(null); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - Kuzzle.this.jwtToken = null; - return this; - } - - /** - * {@link #now(Options, ResponseListener)} - */ - public void now(final ResponseListener listener) { - this.now(null, listener); - } - - /** - * Returns the current Kuzzle UTC timestamp - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void now(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.now: listener required"); - } - this.isValid(); - try { - QueryArgs args = new QueryArgs(); - args.controller = "server"; - args.action = "now"; - this.query(args, null, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(new Date(response.getJSONObject("result").getLong("now"))); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #query(QueryArgs, JSONObject, Options, OnQueryDoneListener)} - */ - public Kuzzle query(final QueryArgs queryArgs, final JSONObject query) throws JSONException { - return this.query(queryArgs, query, null, null); - } - - /** - * {@link #query(QueryArgs, JSONObject, Options, OnQueryDoneListener)} - */ - public Kuzzle query(final QueryArgs queryArgs, final JSONObject query, final Options options) throws JSONException { - return this.query(queryArgs, query, options, null); - } - - /** - * {@link #query(QueryArgs, JSONObject, Options, OnQueryDoneListener)} - */ - public Kuzzle query(final QueryArgs queryArgs, final JSONObject query, final OnQueryDoneListener listener) throws JSONException { - return this.query(queryArgs, query, null, listener); - } - - /** - * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods. - * Base method used to send queries to Kuzzle - * - * @param queryArgs - API route description - * @param query - Query content - * @param options - Request options - * @param listener - Response callback listener - * @return this - * @throws JSONException - */ - public Kuzzle query(final QueryArgs queryArgs, final JSONObject query, final Options options, final OnQueryDoneListener listener) throws JSONException { - this.isValid(); - JSONObject object = query != null ? query : new JSONObject(); - - if (object.isNull("requestId")) { - object.put("requestId", UUID.randomUUID().toString()); - } - - object - .put("action", queryArgs.action) - .put("controller", queryArgs.controller); - - // Global volatile data - JSONObject _volatile = new JSONObject(); - for (Iterator ite = this._volatile.keys(); ite.hasNext(); ) { - String key = (String) ite.next(); - _volatile.put(key, this._volatile.get(key)); - } - - // Volatile data for this query - if (options != null) { - if (!options.isQueuable() && this.state != States.CONNECTED) { - discardRequest(listener, object); - return this; - } - - if (options.getRefresh() != null) { - object.put("refresh", options.getRefresh()); - } - - if (options.getVolatile() != null) { - for (Iterator iterator = options.getVolatile().keys(); iterator.hasNext(); ) { - String key = (String) iterator.next(); - _volatile.put(key, options.getVolatile().get(key)); - } - } - - if (options.getFrom() != null) { - object.put("from", options.getFrom()); - } - - if (options.getSize() != null) { - object.put("size", options.getSize()); - } - - if (options.getScroll() != null) { - object.put("scroll", options.getScroll()); - } - - if (options.getScrollId() != null) { - object.put("scrollId", options.getScrollId()); - } - } - - _volatile.put("sdkVersion", this.getSdkVersion()); - object.put("volatile", _volatile); - - if (queryArgs.collection != null) { - object.put("collection", queryArgs.collection); - } - - if (queryArgs.index != null) { - object.put("index", queryArgs.index); - } - - this.addHeaders(object, this.headers); - - /* - * Do not add the token for the checkToken route, to avoid getting a token error when - * a developer simply wish to verify his token - */ - if (this.jwtToken != null && !(queryArgs.controller.equals("auth") && queryArgs.action.equals("checkToken"))) { - object.put("jwt", this.jwtToken); - } - - if (this.state == States.CONNECTED || (options != null && !options.isQueuable())) { - emitRequest(object, listener == null ? null : new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - listener.onSuccess(response); - } - - @Override - public void onError(JSONObject error) { - if (error != null) { - listener.onError(error); - } - } - }); - } else if (this.queuing || (options != null && options.isQueuable()) || this.state == States.INITIALIZING || this.state == States.CONNECTING) { - cleanQueue(); - - if (queueFilter.filter(object)) { - QueryObject o = new QueryObject(); - o.setTimestamp(new Date()); - o.setCb(listener); - o.setQuery(object); - this.offlineQueue.addToQueue(o); - Kuzzle.this.emitEvent(Event.offlineQueuePush, o); - } - } else { - discardRequest(listener, object); - } - - return this; - } - - /** - * Removes all listeners, either from all events - * - * @return this - */ - public Kuzzle removeAllListeners() { - this.eventListeners.clear(); - return this; - } - - /** - * Remove all listeners kuzzle from the provided event name - * - * @param event - Event name - * @return this - */ - public Kuzzle removeAllListeners(Event event) { - if (eventListeners.containsKey(event)) { - eventListeners.get(event).clear(); - } - - return this; - } - - /** - * Removes a listener from an event. - * - * @param event - Event name - * @param listener - Response callback listener - * @return this - */ - public Kuzzle removeListener(Event event, EventListener listener) { - if (eventListeners.containsKey(event)) { - eventListeners.get(event).remove(listener); - } - - return this; - } - - /** - * Renew all registered subscriptions. Usually called after: - * - a connection, if subscriptions occurred before - * - a reconnection - * - after a successful login attempt, to subscribe with the new credentials - */ - protected void renewSubscriptions() { - for (Map roomSubscriptions : subscriptions.values()) { - for (Room room : roomSubscriptions.values()) { - room.renew(room.getListener(), room.getSubscribeListener()); - } - } - } - - /** - * Replays the requests queued during offline mode. - * Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false. - * - * @return this - */ - public Kuzzle replayQueue() { - if (this.state != States.OFFLINE && !this.autoReplay) { - this.cleanQueue(); - this.dequeue(); - } - return this; - } - - /** - * {@link #setHeaders(JSONObject, boolean)} - */ - public Kuzzle setHeaders(final JSONObject content) throws JSONException { - return this.setHeaders(content, false); - } - - /** - * Helper function allowing to set headers while chaining calls. - * If the replace argument is set to true, replace the current headers with the provided content. - * Otherwise, it appends the content to the current headers, only replacing already existing values - * - * @param content - New headers content - * @param replace - false = append to existing headers (default) - true = replace - * @return this - */ - public Kuzzle setHeaders(final JSONObject content, boolean replace) { - if (this.headers == null) { - this.headers = new JSONObject(); - } - if (replace) { - this.headers = content; - } else { - if (content != null) { - try { - for (Iterator ite = content.keys(); ite.hasNext(); ) { - String key = (String) ite.next(); - this.headers.put(key, content.get(key)); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - return this; - } - - /** - * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false. - * - * @return this - */ - public Kuzzle startQueuing() { - if (this.state == States.OFFLINE && !this.autoQueue) { - this.queuing = true; - } - return this; - } - - /** - * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false. - * - * @return this - */ - public Kuzzle stopQueuing() { - if (this.state == States.OFFLINE && !this.autoQueue) { - this.queuing = false; - } - return this; - } - - /** - * Is valid sate boolean. - * - * @return current state validity - */ - protected boolean isValidState() { - switch (this.state) { - case INITIALIZING: - case READY: - case DISCONNECTED: - case ERROR: - case OFFLINE: - return true; - } - return false; - } - - /** - * Handles network reconnection - */ - private void reconnect() { - if (this.autoResubscribe) { - this.renewSubscriptions(); - } - - if (this.autoReplay) { - this.cleanQueue(); - this.dequeue(); - } - - this.emitEvent(Event.reconnected); - } - - /** - * Create a new connection socket - * @return created socket - * @throws URISyntaxException - */ - protected WebSocketClient createSocket() throws URISyntaxException { - URI uri = null; - try { - uri = new URI((this.isSsl ? "wss" : "ws")+"://"+this.host+":"+this.port+"/"); - } - catch (URISyntaxException e) { - e.printStackTrace(); - } - socket = new WebSocketClient(uri) { - @Override - public void onOpen() { - if (Kuzzle.this.state == States.OFFLINE) { // Reconnect - Kuzzle.this.state = States.CONNECTED; - - if (Kuzzle.this.jwtToken != null) { - Kuzzle.this.checkToken(jwtToken, new ResponseListener() { - @Override - public void onSuccess(TokenValidity response) { - if (!response.isValid()) { - Kuzzle.this.jwtToken = null; - Kuzzle.this.emitEvent(Event.tokenExpired); - } - - Kuzzle.this.reconnect(); - } - - @Override - public void onError(JSONObject error) { - Kuzzle.this.jwtToken = null; - Kuzzle.this.emitEvent(Event.tokenExpired); - Kuzzle.this.reconnect(); - } - }); - } else { - Kuzzle.this.reconnect(); - } - } else { - Kuzzle.this.state = States.CONNECTED; - - Kuzzle.this.renewSubscriptions(); - Kuzzle.this.dequeue(); - Kuzzle.this.emitEvent(Event.connected); - - if (Kuzzle.this.connectionCallback != null) { - Kuzzle.this.connectionCallback.onSuccess(null); - } - } - } - - @Override - public void onTextReceived(String message) { - try { - JSONObject json = new JSONObject(message); - OnQueryDoneListener listener = null; - if (json.has("requestId")) { - listener = currentQueries.get(json.getString("requestId")); - } else { - listener = currentQueries.get(json.getString("room")); - } - - if (listener != null) { - // checking token expiration - if (!json.isNull("error") && json.getJSONObject("error").getString("message").equals("Token expired") && !json.getString("action").equals("logout")) { - emitEvent(Event.tokenExpired, listener); - } - - if (!json.isNull("error")) { - listener.onError(json.getJSONObject("error")); - } else { - listener.onSuccess(json); - } - currentQueries.remove(json.getString("requestId")); - } - - EventListener l = roomList.get(json.getString("room")); - if (l != null) { - l.trigger(new JSONObject(message)); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onBinaryReceived(byte[] data) { - - } - - @Override - public void onPingReceived(byte[] data) { - - } - - @Override - public void onPongReceived(byte[] data) { - - } - - @Override - public void onException(Exception e) { - Kuzzle.this.state = States.ERROR; - Kuzzle.this.emitEvent(Event.error, e.getMessage()); - - if (connectionCallback != null) { - JSONObject error = new JSONObject(); - try { - error.put("message", e.getMessage()); - } catch (JSONException ee) { - throw new RuntimeException(ee); - } - connectionCallback.onError(error); - } - } - - @Override - public void onCloseReceived() { - Kuzzle.this.state = States.OFFLINE; - if (!Kuzzle.this.autoReconnect) { - Kuzzle.this.disconnect(); - } - if (Kuzzle.this.autoQueue) { - Kuzzle.this.queuing = true; - } - currentQueries.clear(); - - Kuzzle.this.emitEvent(Event.disconnected); - } - }; - - if (this.autoReconnect) { - socket.enableAutomaticReconnection(this.reconnectionDelay); - } - - return socket; - } - - /** - * Emit request. - * - * @param request - Request to emit - * @param listener - Response callback listener - * @throws JSONException - */ - protected void emitRequest(final JSONObject request, final OnQueryDoneListener listener) throws JSONException { - Date now = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(now); - c.add(Calendar.SECOND, -MAX_EMIT_TIMEOUT); - - if (listener != null) { - currentQueries.put(request.get("requestId").toString(), listener); - } - - socket.send(request.toString()); - - // Track requests made to allow Room.subscribeToSelf to work - this.requestHistory.put(request.getString("requestId"), new Date()); - - // Clean history from requests made more than 10s ago - Iterator ite = requestHistory.keySet().iterator(); - - while (ite.hasNext()) { - if (this.requestHistory.get(ite.next()).before(c.getTime())) { - ite.remove(); - } - } - } - - /** - * Helper function ensuring that this Kuzzle object is still valid before performing a query - */ - protected void isValid() { - if (this.state == States.DISCONNECTED) { - throw new IllegalStateException("This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?"); - } - } - - /** - * Helper function copying headers to the query data - * - * @param query - Query to update - * @param headers - Headers to set - */ - public void addHeaders(JSONObject query, final JSONObject headers) { - try { - for (Iterator iterator = headers.keys(); iterator.hasNext(); ) { - String key = (String) iterator.next(); - if (query.isNull(key)) { - query.put(key, headers.get(key)); - } - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * autoReconnect option getter - * - * @return autoReconnect option value - */ - public boolean isAutoReconnect() { - return autoReconnect; - } - - /** - * autoResubscribe option getter - * - * @return autoResubscribe option value - */ - public boolean isAutoResubscribe() { - return this.autoResubscribe; - } - - /** - * autoResubscribe option setter - * - * @param resubscribe - autoResubscribe new value - * @return this - */ - public Kuzzle setAutoResubscribe(boolean resubscribe) { - this.autoResubscribe = resubscribe; - return this; - } - - /** - * Global headers getter - * - * @return global headers - */ - public JSONObject getHeaders() { - return this.headers; - } - - /** - * Returns the current SDK version. - * - * @return Current SDK version - */ - public String getSdkVersion() { - return "2.0.0"; - } - - /** - * Add pending subscription kuzzle. - * - * @param id - Room instance unique ID - * @param room - Associated Room instance - * @return this - */ - protected Kuzzle addPendingSubscription(final String id, final Room room) { - this.subscriptions.get("pending").put(id, room); - return this; - } - - /** - * Delete a pending subscription - * - * @param id - Unique ID of the Room instance to delete - * @return this - */ - protected Kuzzle deletePendingSubscription(final String id) { - ConcurrentHashMap pending = this.subscriptions.get("pending"); - - if (pending != null) { - pending.remove(id); - } - - return this; - } - - /** - * Add a new subscription - * - * @param roomId - Subscription identifier - * @param id - Room instance unique ID - * @param kuzzleRoom - Associated Room instance - * @return this - */ - protected Kuzzle addSubscription(final String roomId, final String id, final Room kuzzleRoom) { - ConcurrentHashMap room = this.subscriptions.get(roomId); - - if (room == null) { - room = new ConcurrentHashMap<>(); - this.subscriptions.put(id, room); - } - - room.put(id, kuzzleRoom); - - return this; - } - - protected Kuzzle addRoom(final String channel, EventListener listener) { - if (channel != null) { - roomList.put(channel, listener); - } - - return this; - } - - protected Kuzzle removeRoom(final String channel) { - if (channel != null) { - roomList.remove(channel); - } - - return this; - } - - /** - * Connection socket getter - * - * @return Connection socket - */ - protected WebSocketClient getSocket() { - return socket; - } - - /** - * Connection socket setter - * - * @param socket - New connection socket - */ - protected void setSocket(WebSocketClient socket) { - this.socket = socket; - } - - /** - * Add a query to the offline queue - * - * @param query - Query to queue - * @return this - */ - public Kuzzle setOfflineQueue(final QueryObject query) { - this.offlineQueue.addToQueue(query); - return this; - } - - /** - * Offline queue getter - * - * @return offline queue - */ - public Queue getOfflineQueue() { - return this.offlineQueue.getQueue(); - } - - - /** - * Sets offline queue filter. - * - * @param queueFilter - Offline queue global filter - * @return this - */ - public Kuzzle setQueueFilter(QueueFilter queueFilter) { - this.queueFilter = queueFilter; - return this; - } - - /** - * Offline queue filter getter - * - * @return Offline queue filter - */ - public QueueFilter getQueueFilter() { - return this.queueFilter; - } - - /** - * autoReplay option getter - * - * @return autoReplay option value - */ - public boolean isAutoReplay() { - return autoReplay; - } - - - /** - * Kuzzle server port getter - * - * @return Kuzzle server port - */ - public int getPort() { - return port; - } - - /** - * Kuzzle server port setter - * - * @param port - New Kuzzle server port - * @return this - */ - public Kuzzle setPort(int port) { - this.port = port; - return this; - } - - /** - * Kuzzle server host name getter - * - * @return Kuzzle server host name - */ - public String getHost() { - return this.host; - } - - /** - * Kuzzle server host name setter - * - * @param host - New host name - * @return this - */ - public Kuzzle setHost(String host) { - this.host = host; - return this; - } - - /** - * autoReplay option setter - * - * @param autoReplay - New autoReplay option value - * @return this - */ - public Kuzzle setAutoReplay(boolean autoReplay) { - this.autoReplay = autoReplay; - return this; - } - - /** - * queueMaxSize option setter - * - * @param newMaxSize - New queueMaxSize value - * @return this - */ - public Kuzzle setQueueMaxSize(int newMaxSize) { - this.queueMaxSize = Math.max(0, newMaxSize); - return this; - } - - /** - * queueMaxSize option getter - * - * @return queueMaxSize option value - */ - public int getQueueMaxSize() { - return this.queueMaxSize; - } - - /** - * autoQueue option getter - * - * @return autoQueue option value - */ - public boolean isAutoQueue() { - return autoQueue; - } - - /** - * autoQueue option setter - * - * @param autoQueue - New autoQueue option value - * @return this - */ - public Kuzzle setAutoQueue(final boolean autoQueue) { - this.autoQueue = autoQueue; - return this; - } - - /** - * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected - */ - private void cleanQueue() { - Date now = new Date(); - Calendar cal = Calendar.getInstance(); - cal.setTime(now); - cal.add(Calendar.MILLISECOND, -queueTTL); - - if (this.queueTTL > 0) { - QueryObject o; - while ((o = (QueryObject) offlineQueue.getQueue().peek()) != null) { - if (o.getTimestamp().before(cal.getTime())) { - offlineQueue.getQueue().poll(); - } else { - break; - } - } - } - - int size = this.offlineQueue.getQueue().size(); - if (this.queueMaxSize > 0 && size > this.queueMaxSize) { - int i = 0; - while (offlineQueue.getQueue().peek() != null && (size - this.queueMaxSize) >= i) { - this.offlineQueue.getQueue().poll(); - i++; - } - } - } - - private void mergeOfflineQueueWithLoader() { - KuzzleQueue additionalOfflineQueue = this.offlineQueueLoader.load(); - try { - for (QueryObject additionalQuery : additionalOfflineQueue) { - for (QueryObject offlineQuery : this.offlineQueue) { - if (additionalQuery.getQuery() != null && additionalQuery.getQuery().has("requestId") && additionalQuery.getQuery().has("action") && additionalQuery.getQuery().has("controller")) { - if (!offlineQuery.getQuery().getString("requestId").equals(additionalQuery.getQuery().getString("requestId"))) { - this.offlineQueue.addToQueue(additionalOfflineQueue.dequeue()); - } else { - additionalOfflineQueue.dequeue(); - } - } else { - throw new IllegalArgumentException("Invalid offline queue request. One or more missing properties: requestId, action, controller."); - } - } - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * Play all queued requests, in order. - */ - private void dequeue() { - if (offlineQueueLoader != null) { - this.mergeOfflineQueueWithLoader(); - } - if (this.offlineQueue.getQueue().size() > 0) { - try { - QueryObject query = (QueryObject) this.offlineQueue.getQueue().poll(); - this.emitRequest(query.getQuery(), query.getCb()); - this.emitEvent(Event.offlineQueuePop, query); - } catch (JSONException e) { - throw new RuntimeException(e); - } - Timer timer = new Timer(UUID.randomUUID().toString()); - timer.schedule(new TimerTask() { - @Override - public void run() { - dequeue(); - } - }, Math.max(0, this.replayInterval)); - } else { - this.queuing = false; - } - } - - /** - * Delete a suscription - * - * @param roomId - Subscription unique ID - * @param id - Room instance unique ID - * @return this - */ - protected Kuzzle deleteSubscription(final String roomId, final String id) { - if (this.subscriptions.containsKey(roomId)) { - this.subscriptions.get(roomId).remove(id); - - if (this.subscriptions.get(roomId).isEmpty()) { - this.subscriptions.remove(roomId); - } - } - - return this; - } - - /** - * Gets subscriptions. - * - * @param roomId - Subscription unique ID - * @return matching registered subscriptions - */ - protected Map getSubscriptions(String roomId) { - if (roomId != null && this.subscriptions.containsKey(roomId)) { - return this.subscriptions.get(roomId); - } - - return null; - } - - /** - * Getter for the pendingSubscriptions private property - * - * @return pendingSubscriptions property value - */ - protected Map getPendingSubscriptions() { - return this.subscriptions.get("pending"); - } - - /** - * requestHistory getter - * - * @return Request history - */ - protected Map getRequestHistory() { - return requestHistory; - } - - /** - * Default index getter - * - * @return Default index value - */ - public String getDefaultIndex() { - return this.defaultIndex; - } - - /** - * Default index setter - * - * @param index - New default index name - * @return this - */ - public Kuzzle setDefaultIndex(final String index) { - if (index == null || index.isEmpty()) { - throw new IllegalArgumentException("Kuzzle.setDefaultIndex: index required"); - } - this.defaultIndex = index; - return this; - } - - /** - * Set a new JWT and trigger the 'loginAttempt' event. - * - * @param jwt - New authentication JSON Web Token - * @return this - */ - public Kuzzle setJwtToken(final String jwt) { - this.jwtToken = jwt; - try { - this.renewSubscriptions(); - this.emitEvent(Event.loginAttempt, new JSONObject().put("success", true)); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * Unset the authentication token and cancel all subscriptions - * - * @return this - */ - public Kuzzle unsetJwtToken() { - this.jwtToken = null; - - for (Map roomSubscriptions : subscriptions.values()) { - for (Room room : roomSubscriptions.values()) { - room.unsubscribe(); - } - } - return this; - } - - /** - * Sets the authentication token from a Kuzzle response object - * - * @param response - A Kuzzle API response - * @return this - * @throws JSONException - */ - public Kuzzle setJwtToken(final JSONObject response) throws JSONException { - JSONObject result; - - if (response == null) { - throw new IllegalArgumentException("Cannot set token from a null Kuzzle response"); - } - - if (response.has("result") && (result = response.getJSONObject("result")).has("jwt")) { - this.jwtToken = result.getString("jwt"); - this.renewSubscriptions(); - this.emitEvent(Event.loginAttempt, new JSONObject().put("success", true)); - } else { - this.emitEvent(Event.loginAttempt, new JSONObject() - .put("success", false) - .put("error", "Cannot find a valid JWT token in the following object: " + response.toString()) - ); - } - - return this; - } - - /** - * Authentication token getter - * - * @return Current JWT - */ - public String getJwtToken() { - return this.jwtToken; - } - - /** - * queueTTL option getter - * - * @param newTTL - New queueTTL value - * @return this - */ - public Kuzzle setQueueTTL(int newTTL) { - this.queueTTL = Math.max(0, newTTL); - return this; - } - - /** - * queueTTL option getter - * - * @return queue ttl value - */ - public int getQueueTTL() { - return this.queueTTL; - } - - /** - * Global volatile data setter - * - * @param _volatile - New global volatile data content - * @return this - */ - public Kuzzle setVolatile(JSONObject _volatile) { - this._volatile = _volatile; - return this; - } - - /** - * Global volatile data getter - * - * @return Global volatile data - */ - public JSONObject getVolatile() { - return this._volatile; - } - - - /** - * replayInterval option setter - * - * @param interval - New replayInterval value - * @return this - */ - public Kuzzle setReplayInterval(long interval) { - this.replayInterval = Math.max(0, interval); - return this; - } - - /** - * replayInterval option getter - * - * @return replayInterval value - */ - public long getReplayInterval() { - return this.replayInterval; - } - - /** - * reconnectionDelay option getter - * - * @return reconnectionDelay value - */ - public long getReconnectionDelay() { - return this.reconnectionDelay; - } - - /** - * Offline queue loader setter - * - * @param offlineQueueLoader - Offline queue loader function - */ - public void setOfflineQueueLoader(OfflineQueueLoader offlineQueueLoader) { - this.offlineQueueLoader = offlineQueueLoader; - } - - /** - * {@link #updateSelf(JSONObject, Options, ResponseListener)} - */ - public Kuzzle updateSelf(final JSONObject content) { - return updateSelf(content, null, null); - } - - /** - * {@link #updateSelf(JSONObject, Options, ResponseListener)} - */ - public Kuzzle updateSelf(final JSONObject content, final Options options) { - return updateSelf(content, options, null); - } - - /** - * {@link #updateSelf(JSONObject, Options, ResponseListener)} - */ - public Kuzzle updateSelf(final JSONObject content, final ResponseListener listener) { - return updateSelf(content, null, listener); - } - - /** - * Update the currently authenticated user informations - * - * @param content - Current user infos to update - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle updateSelf(final JSONObject content, final Options options, final ResponseListener listener) { - QueryArgs args = new QueryArgs(); - args.controller = "auth"; - args.action = "updateSelf"; - - try { - JSONObject query = new JSONObject().put("body", content); - this.query(args, query, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener != null) { - listener.onSuccess(response); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * Retrieves current user information - * - * @param listener - Response callback listener - */ - public void whoAmI(final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.whoAmI: listener required"); - } - - try { - QueryArgs args = new QueryArgs(); - args.controller = "auth"; - args.action = "getCurrentUser"; - JSONObject request = new JSONObject(); - - this.query(args, request, null, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - listener.onSuccess(new User(Kuzzle.this, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #refreshIndex(Options, ResponseListener)} - */ - public Kuzzle refreshIndex() { - return this.refreshIndex(null, null, null); - } - - /** - * {@link #refreshIndex(String, Options, ResponseListener)} - */ - public Kuzzle refreshIndex(String index) { - return this.refreshIndex(index, null, null); - } - - /** - * {@link #refreshIndex(String, Options, ResponseListener)} - */ - public Kuzzle refreshIndex(String index, final ResponseListener listener) { - return this.refreshIndex(index, null, listener); - } - - /** - * {@link #refreshIndex(String, Options, ResponseListener)} - */ - public Kuzzle refreshIndex(String index, final Options options) { - return this.refreshIndex(index, options, null); - } - - /** - * {@link #refreshIndex(Options, ResponseListener)} - */ - public Kuzzle refreshIndex(final Options options) { - return this.refreshIndex(null, options, null); - } - - /** - * Forces the default data index to refresh on each modification - * - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle refreshIndex(final Options options, final ResponseListener listener) { - return this.refreshIndex(null, options, listener); - } - - /** - * {@link #refreshIndex(Options, ResponseListener)} - */ - public Kuzzle refreshIndex(final ResponseListener listener) { - return this.refreshIndex(null, null, listener); - } - - /** - * Forces the provided data index to refresh on each modification - * - * @param index - Data index name - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle refreshIndex(String index, final Options options, final ResponseListener listener) { - if (index == null) { - if (this.defaultIndex == null) { - throw new IllegalArgumentException("Kuzzle.refreshIndex: index required"); - } else { - index = this.defaultIndex; - } - } - - QueryArgs args = new QueryArgs(); - args.index = index; - args.controller = "index"; - args.action = "refresh"; - JSONObject request = new JSONObject(); - - try { - this.query(args, request, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener == null) { - return; - } - - try { - JSONObject result = response.getJSONObject("result"); - - listener.onSuccess(result); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener == null) { - return; - } - - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #getAutoRefresh(Options, ResponseListener)} - */ - public void getAutoRefresh(final ResponseListener listener) { - this.getAutoRefresh(null, null, listener); - } - - /** - * {@link #getAutoRefresh(String, Options, ResponseListener)} - */ - public void getAutoRefresh(String index, final ResponseListener listener) { - this.getAutoRefresh(index, null, listener); - } - - /** - * Gets the autoRefresh value for the default data index - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void getAutoRefresh(Options options, final ResponseListener listener) { - this.getAutoRefresh(null, options, listener); - } - - /** - * Gets the autoRefresh value for the provided data index name - * - * @param index - Data index name - * @param options - Request options - * @param listener - Response callback listener - */ - public void getAutoRefresh(String index, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.getAutoRefresh: listener required"); - } - - if (index == null) { - if (this.defaultIndex == null) { - throw new IllegalArgumentException("Kuzzle.getAutoRefresh: index required"); - } else { - index = this.defaultIndex; - } - } - - QueryArgs args = new QueryArgs(); - args.index = index; - args.controller = "index"; - args.action = "getAutoRefresh"; - JSONObject request = new JSONObject(); - - try { - this.query(args, request, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - boolean result = response.getBoolean("result"); - listener.onSuccess(result); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #setAutoRefresh(boolean, Options, ResponseListener)} - */ - public Kuzzle setAutoRefresh(final boolean autoRefresh) { - return this.setAutoRefresh(null, autoRefresh, null, null); - } - - /** - * {@link #setAutoRefresh(boolean, Options, ResponseListener)} - */ - public Kuzzle setAutoRefresh(final boolean autoRefresh, final ResponseListener listener) { - return this.setAutoRefresh(null, autoRefresh, null, listener); - } - - /** - * {@link #setAutoRefresh(String, boolean, Options, ResponseListener)} - */ - public Kuzzle setAutoRefresh(String index, final boolean autoRefresh) { - return this.setAutoRefresh(index, autoRefresh, null, null); - } - - /** - * {@link #setAutoRefresh(boolean, Options, ResponseListener)} - */ - public Kuzzle setAutoRefresh(final boolean autoRefresh, final Options options) { - return this.setAutoRefresh(null, autoRefresh, options, null); - } - - /** - * {@link #setAutoRefresh(String, boolean, Options, ResponseListener)} - */ - public Kuzzle setAutoRefresh(String index, final boolean autoRefresh, final Options options) { - return this.setAutoRefresh(index, autoRefresh, options, null); - } - - /** - * {@link #setAutoRefresh(String, boolean, Options, ResponseListener)} - */ - public Kuzzle setAutoRefresh(String index, final boolean autoRefresh, final ResponseListener listener) { - return this.setAutoRefresh(index, autoRefresh, null, listener); - } - - /** - * autoRefresh status setter for the default data index - * - * @param autoRefresh - New autoRefresh property value - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle setAutoRefresh(final boolean autoRefresh, final Options options, final ResponseListener listener) { - return this.setAutoRefresh(null, autoRefresh, options, listener); - } - - /** - * autorefresh status setter for the provided data index name - * - * @param index - Data index name - * @param autoRefresh - New autoRefresh property value - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle setAutoRefresh(String index, final boolean autoRefresh, final Options options, final ResponseListener listener) { - if (index == null) { - if (this.defaultIndex == null) { - throw new IllegalArgumentException("Kuzzle.setAutoRefresh: index required"); - } else { - index = this.defaultIndex; - } - } - - QueryArgs args = new QueryArgs(); - args.index = index; - args.controller = "index"; - args.action = "setAutoRefresh"; - JSONObject request; - - try { - request = new JSONObject().put("body", new JSONObject().put("autoRefresh", autoRefresh)); - this.query(args, request, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - if (listener == null) { - return; - } - - try { - boolean result = response.getBoolean("result"); - listener.onSuccess(result); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #getMyRights(Options, ResponseListener)} - */ - public Kuzzle getMyRights(final ResponseListener listener) { - return getMyRights(null, listener); - } - - /** - * Gets the rights array for the currently logged user. - * - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle getMyRights(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Security.getMyRights: listener is mandatory."); - } - try { - Kuzzle.this.query(buildQueryArgs("auth", "getMyRights"), new JSONObject(), options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONArray hits = response.getJSONObject("result").getJSONArray("hits"); - JSONObject[] rights = new JSONObject[hits.length()]; - - for (int i = 0; i < hits.length(); i++) { - rights[i] = hits.getJSONObject(i); - } - - listener.onSuccess(rights); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - protected io.kuzzle.sdk.core.Kuzzle.QueryArgs buildQueryArgs(final String controller, String action) { - io.kuzzle.sdk.core.Kuzzle.QueryArgs args = new io.kuzzle.sdk.core.Kuzzle.QueryArgs(); - args.action = action; - args.controller = "security"; - if (controller != null) { - args.controller = controller; - } - args.action = action; - return args; - } - - /** - * Helper function meant to easily build the first Kuzzle.query() argument - * - * @param action - API controller action name - * @return JSONObject - Kuzzle.query() 1st argument object - * @throws JSONException - */ - protected io.kuzzle.sdk.core.Kuzzle.QueryArgs buildQueryArgs(final String action) throws JSONException { - return buildQueryArgs(null, action); - } - - /** - * Invokes a query listener with a custom error message and status - * - * @param listener - Response callback listener - * @param query - discarded query - * @throws JSONException - */ - protected void discardRequest(final OnQueryDoneListener listener, JSONObject query) throws JSONException { - if (listener != null) { - JSONObject err = new JSONObject() - .put("status", 400) - .put("message", "Unable to execute request: not connected to a Kuzzle server.\nDiscarded request: " + query.toString()); - - listener.onError(err); - } - } - - /** - * {@link #createMyCredentials(String, JSONObject, Options, ResponseListener)} - */ - public Kuzzle createMyCredentials(final String strategy, final JSONObject credentials) { - return createMyCredentials(strategy, credentials, null, null); - } - - /** - * {@link #createMyCredentials(String, JSONObject, Options, ResponseListener)} - */ - public Kuzzle createMyCredentials(final String strategy, final JSONObject credentials, final Options options) { - return createMyCredentials(strategy, credentials, options, null); - } - - /** - * {@link #createMyCredentials(String, JSONObject, Options, ResponseListener)} - */ - public Kuzzle createMyCredentials(final String strategy, final JSONObject credentials, final ResponseListener listener) { - return createMyCredentials(strategy, credentials, null, listener); - } - - /** - * Create credentials of the specified strategy for the current user. - * - * @param strategy - impacted strategy name - * @param credentials - credentials to create - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle createMyCredentials(final String strategy, final JSONObject credentials, final Options options, final ResponseListener listener) { - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("body", credentials); - Kuzzle.this.query(buildQueryArgs("auth", "createMyCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (listener != null) { - listener.onSuccess(response.getJSONObject("result")); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #deleteMyCredentials(String, Options, ResponseListener)} - */ - public Kuzzle deleteMyCredentials(final String strategy) { - return deleteMyCredentials(strategy, null, null); - } - - /** - * {@link #deleteMyCredentials(String, Options, ResponseListener)} - */ - public Kuzzle deleteMyCredentials(final String strategy, final Options options) { - return deleteMyCredentials(strategy, options, null); - } - - /** - * {@link #deleteMyCredentials(String, Options, ResponseListener)} - */ - public Kuzzle deleteMyCredentials(final String strategy, final ResponseListener listener) { - return deleteMyCredentials(strategy, null, listener); - } - - /** - * Delete credentials of the specified strategy for the current user. - * - * @param strategy- Name of the strategy to remove - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle deleteMyCredentials(final String strategy, final Options options, final ResponseListener listener) { - try { - JSONObject body = new JSONObject() - .put("strategy", strategy); - Kuzzle.this.query(buildQueryArgs("auth", "deleteMyCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (listener != null) { - listener.onSuccess(response.getJSONObject("result")); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #getMyCredentials(String, Options, ResponseListener)} - */ - public void getMyCredentials(final String strategy, final ResponseListener listener) { - getMyCredentials(strategy, null, listener); - } - - /** - * Get credential information of the specified strategy for the current user. - * - * @param strategy - Strategy name to get - * @param options - Request options - * @param listener - Response callback listener - */ - public void getMyCredentials(final String strategy, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.getMyCredentials: listener is mandatory"); - } - try { - JSONObject body = new JSONObject() - .put("strategy", strategy); - Kuzzle.this.query(buildQueryArgs("auth", "getMyCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #updateMyCredentials(String, JSONObject, Options, ResponseListener)} - */ - public Kuzzle updateMyCredentials(final String strategy, final JSONObject credentials) { - return updateMyCredentials(strategy, credentials, null, null); - } - - /** - * {@link #updateMyCredentials(String, JSONObject, Options, ResponseListener)} - */ - public Kuzzle updateMyCredentials(final String strategy, final JSONObject credentials, final Options options) { - return updateMyCredentials(strategy, credentials, options, null); - } - - /** - * {@link #updateMyCredentials(String, JSONObject, Options, ResponseListener)} - */ - public Kuzzle updateMyCredentials(final String strategy, final JSONObject credentials, final ResponseListener listener) { - return updateMyCredentials(strategy, credentials, null, listener); - } - - /** - * Update credentials of the specified strategy for the current user. - * - * @param strategy - Strategy name to update - * @param credentials - Updated credentials content - * @param options - Request options - * @param listener - Response callback listener - * @return this - */ - public Kuzzle updateMyCredentials(final String strategy, final JSONObject credentials, final Options options, final ResponseListener listener) { - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("body", credentials); - Kuzzle.this.query(buildQueryArgs("auth", "updateMyCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (listener != null) { - listener.onSuccess(response.getJSONObject("result")); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #validateMyCredentials(String, JSONObject, Options, ResponseListener)} - */ - public void validateMyCredentials(final String strategy, final JSONObject credentials, final ResponseListener listener) { - validateMyCredentials(strategy, credentials, null, listener); - } - - /** - * Validate credentials of the specified strategy for the current user. - * - * @param strategy - Strategy name to validate - * @param credentials - Credentials content - * @param options - Request options - * @param listener - Response callback listener - */ - public void validateMyCredentials(final String strategy, final JSONObject credentials, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Kuzzle.validateMyCredentials: listener is mandatory"); - } - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("body", credentials); - Kuzzle.this.query(buildQueryArgs("auth", "validateMyCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getBoolean("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/main/java/io/kuzzle/sdk/core/MemoryStorage.java b/src/main/java/io/kuzzle/sdk/core/MemoryStorage.java deleted file mode 100644 index ca53d6f6..00000000 --- a/src/main/java/io/kuzzle/sdk/core/MemoryStorage.java +++ /dev/null @@ -1,4355 +0,0 @@ -package io.kuzzle.sdk.core; - - - -import org.json.JSONException; -import org.json.JSONObject; -import org.json.JSONArray; - -import java.util.ArrayList; -import java.util.Arrays; - -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.util.KuzzleJSONObject; - -/** - * Kuzzle's memory storage is a separate data store from the database layer. - * It is internaly based on Redis. You can access most of Redis functions (all - * lowercased), excepting: - * * all cluster based functions - * * all script based functions - * * all cursors functions - * - */ -public class MemoryStorage { - private Kuzzle kuzzle; - private Kuzzle.QueryArgs queryArgs = new Kuzzle.QueryArgs(); - - public MemoryStorage(final Kuzzle kuzzle) { - this.kuzzle = kuzzle; - queryArgs.controller = "ms"; - } - - protected void assignGeoradiusOptions(JSONObject query, Options options) { - if (options != null) { - JSONArray opts = new JSONArray(); - - if (options.getWithcoord()) { - opts.put("withcoord"); - } - - if (options.getWithdist()) { - opts.put("withdist"); - } - - if (options.getCount() != null) { - opts.put("count").put(options.getCount()); - } - - if (options.getSort() != null) { - opts.put(options.getSort()); - } - - if (opts.length() > 0) { - try { - query.put("options", opts); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - } - - protected JSONObject[] mapGeoradiusResults(JSONArray points) throws JSONException { - JSONObject[] mapped = new JSONObject[points.length()]; - - // Simple array of point names (no options provided) - if (points.get(0) instanceof String) { - for (int i = 0; i < points.length(); i++) { - mapped[i] = new JSONObject().put("name", points.getString(i)); - } - - return mapped; - } - - for (int i = 0; i < points.length(); i++) { - JSONArray rawPoint = points.getJSONArray(i); - JSONObject p = new JSONObject().put("name", rawPoint.getString(0)); - - for (int j = 1; j < rawPoint.length(); j++) { - // withcoord results are stored in an array... - if (rawPoint.get(j) instanceof JSONArray) { - JSONArray coords = rawPoint.getJSONArray(j); - - p - .put("coordinates", new JSONArray() - .put(Double.parseDouble(coords.getString(0))) - .put(Double.parseDouble(coords.getString(1))) - ); - } - else { - // ... while withdist results are not - p.put("distance", Double.parseDouble(rawPoint.getString(j))); - } - } - - mapped[i] = p; - } - - return mapped; - } - - protected JSONObject[] mapZrangeResults(JSONArray members) { - ArrayList mapped = new ArrayList<>(members.length() /2); - - try { - for (int i = 0; i < members.length(); i += 2) { - mapped.add(new JSONObject() - .put("member", members.getString(i)) - .put("score", Double.parseDouble(members.getString(i+1))) - ); - } - } - catch(JSONException e) { - throw new RuntimeException(e); - } - - return mapped.toArray(new JSONObject[0]); - } - - protected void send(String action, final KuzzleJSONObject query, Options options, final ResponseListener listener) { - queryArgs.action = action; - - try { - if (listener != null) { - kuzzle.query(queryArgs, query, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - listener.onSuccess(response); - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - kuzzle.query(queryArgs, query, options); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - protected ResponseListener getCallbackLong(final ResponseListener listener) { - return new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getLong("result")); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }; - } - - protected ResponseListener getCallbackInt(final ResponseListener listener) { - return new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getInt("result")); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }; - } - - protected ResponseListener getCallbackString(final ResponseListener listener) { - return new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getString("result")); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }; - } - - protected ResponseListener getCallbackDouble(final ResponseListener listener) { - return new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(Double.parseDouble(response.getString("result"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }; - } - - protected ResponseListener getCallbackStringArray(final ResponseListener listener) { - return new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONArray arr = response.getJSONArray("result"); - String[] result = new String[arr.length()]; - - for (int i = 0; i < arr.length(); i++) { - result[i] = arr.getString(i); - } - - listener.onSuccess(result); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }; - } - - protected ResponseListener getCallbackScanResult(final ResponseListener listener) { - return new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONArray arr = response.getJSONArray("result"); - JSONObject result = new JSONObject(); - - try { - result - .put("cursor", Integer.parseInt(arr.getString(0))) - .put("values", arr.getJSONArray(1)); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - - listener.onSuccess(result); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }; - } - - /** - * {@link #append(String, String, Options, ResponseListener)} - */ - public MemoryStorage append(String key, final String value) { - return append(key, value, null, null); - } - - /** - * {@link #append(String, String, Options, ResponseListener)} - */ - public MemoryStorage append(String key, final String value, Options options) { - return append(key, value, options, null); - } - - /** - * {@link #append(String, String, Options, ResponseListener)} - */ - public MemoryStorage append(String key, final String value, final ResponseListener listener) { - return append(key, value, null, listener); - } - - /** - * Append a value to a key - * - * @param key Key ID - * @param value Value to append - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage append(String key, final String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - ); - - send("append", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #bitcount(String, Options, ResponseListener)} - */ - public void bitcount(String key, final ResponseListener listener) { - bitcount(key, null, listener); - } - - /** - * Counts the number of set bits (population counting) - * - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - */ - public void bitcount(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - if (options != null) { - if (options.getStart() != null) { - query.put("start", options.getStart()); - } - - if (options.getEnd() != null) { - query.put("end", options.getEnd()); - } - } - - send("bitcount", query, options, getCallbackLong(listener)); - } - - /** - * {@link #bitop(String, String, String[], Options, ResponseListener)} - */ - public MemoryStorage bitop(String key, String operation, final String[] keys) throws JSONException { - return bitop(key, operation, keys, null, null); - } - - /** - * {@link #bitop(String, String, String[], Options, ResponseListener)} - */ - public MemoryStorage bitop(String key, String operation, final String[] keys, Options options) throws JSONException { - return bitop(key, operation, keys, options, null); - } - - /** - * {@link #bitop(String, String, String[], Options, ResponseListener)} - */ - public MemoryStorage bitop(String key, String operation, final String[] keys, final ResponseListener listener) throws JSONException { - return bitop(key, operation, keys, null, listener); - } - - /** - * Performs a bitwise operation between multiple keys (containing string values) and stores the result in the destination key. - * @param key Destination Key ID - * @param operation Bit operation name - * @param keys Keys on which to perform the bitwise operation - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public MemoryStorage bitop(String key, String operation, final String[] keys, Options options, final ResponseListener listener) throws JSONException { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("operation", operation) - .put("keys", new JSONArray(Arrays.asList(keys))) - ); - - send("bitop", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #bitpos(String, int, Options, ResponseListener)} - */ - public void bitpos(String key, int bit, final ResponseListener listener) { - bitpos(key, bit, null, listener); - } - - /** - * Returns the position of the first bit set to 1 or 0 in a string, or in a substring - * @param key Key ID - * @param bit Bit to look for - * @param options Request options - * @param listener Response callback listener - */ - public void bitpos(String key, int bit, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("bit", bit); - - if (options != null) { - if (options.getStart() != null) { - query.put("start", options.getStart()); - } - - if (options.getEnd() != null) { - query.put("end", options.getEnd()); - } - } - - send("bitpos", query, options, getCallbackLong(listener)); - } - - /** - * {@link #dbsize(Options, ResponseListener)} - */ - public void dbsize(final ResponseListener listener) { - dbsize(null, listener); - } - - /** - * Returns the number of keys in the application database. - * @param options Request options - * @param listener Response callback listener - */ - public void dbsize(Options options, final ResponseListener listener) { - send("dbsize", new KuzzleJSONObject(), options, getCallbackLong(listener)); - } - - /** - * {@link #decr(String, Options, ResponseListener)} - */ - public MemoryStorage decr(String key) { - return decr(key, null, null); - } - - /** - * {@link #decr(String, Options, ResponseListener)} - */ - public MemoryStorage decr(String key, Options options) { - return decr(key, options, null); - } - - /** - * {@link #decr(String, Options, ResponseListener)} - */ - public MemoryStorage decr(String key, final ResponseListener listener) { - return decr(key, null, listener); - } - - /** - * Decrements the value of a key by 1 - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage decr(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("decr", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #decrby(String, long, Options, ResponseListener)} - */ - public MemoryStorage decrby(String key, long value) { - return decrby(key, value, null, null); - } - - /** - * {@link #decrby(String, long, Options, ResponseListener)} - */ - public MemoryStorage decrby(String key, long value, Options options) { - return decrby(key, value, options, null); - } - - /** - * {@link #decrby(String, long, Options, ResponseListener)} - */ - public MemoryStorage decrby(String key, long value, final ResponseListener listener) { - return decrby(key, value, null, listener); - } - - /** - * Decrements the value of a key by a given value - * @param key Key ID - * @param value Decrement value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage decrby(String key, long value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - ); - - send("decrby", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #del(String[], Options, ResponseListener)} - */ - public MemoryStorage del(String[] keys) { - return del(keys, null, null); - } - - /** - * {@link #del(String[], Options, ResponseListener)} - */ - public MemoryStorage del(String[] keys, Options options) { - return del(keys, options, null); - } - - /** - * {@link #del(String[], Options, ResponseListener)} - */ - public MemoryStorage del(String[] keys, final ResponseListener listener) { - return del(keys, null, listener); - } - - /** - * Delete keys - * @param keys Key IDs to delete - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage del(String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("body", new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys)))); - - send("del", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #exists(String[], Options, ResponseListener)} - */ - public void exists(String[] keys, final ResponseListener listener) { - exists(keys, null, listener); - } - - /** - * Check if the specified keys exist - * - * @param keys Key IDs - * @param options Request options - * @param listener Response callback listener - */ - public void exists(String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys))); - - send("exists", query, options, getCallbackLong(listener)); - } - - /** - * {@link #expire(String, long, Options, ResponseListener)} - */ - public MemoryStorage expire(String key, long seconds) { - return expire(key, seconds, null, null); - } - - /** - * {@link #expire(String, long, Options, ResponseListener)} - */ - public MemoryStorage expire(String key, long seconds, Options options) { - return expire(key, seconds, options, null); - } - - /** - * {@link #expire(String, long, Options, ResponseListener)} - */ - public MemoryStorage expire(String key, long seconds, final ResponseListener listener) { - return expire(key, seconds, null, listener); - } - - /** - * Set an expiration timeout on a key - * @param key Key ID - * @param seconds Timeout (in seconds) - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage expire(String key, long seconds, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("seconds", seconds) - ); - - send("expire", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #expireat(String, long, Options, ResponseListener)} - */ - public MemoryStorage expireat(String key, long timestamp) { - return expireat(key, timestamp, null, null); - } - - /** - * {@link #expireat(String, long, Options, ResponseListener)} - */ - public MemoryStorage expireat(String key, long timestamp, Options options) { - return expireat(key, timestamp, options, null); - } - - /** - * {@link #expireat(String, long, Options, ResponseListener)} - */ - public MemoryStorage expireat(String key, long timestamp, final ResponseListener listener) { - return expireat(key, timestamp, null, listener); - } - - /** - * Set an expiration timestamp to a key - * @param key Key ID - * @param timestamp Expiration timestamp (Epoch Time) - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage expireat(String key, long timestamp, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("timestamp", timestamp) - ); - - send("expireat", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #flushdb(Options, ResponseListener)} - */ - public MemoryStorage flushdb() { - return flushdb(null, null); - } - - /** - * {@link #flushdb(Options, ResponseListener)} - */ - public MemoryStorage flushdb(final ResponseListener listener) { - return flushdb(null, listener); - } - - - /** - * {@link #flushdb(Options, ResponseListener)} - */ - public MemoryStorage flushdb(Options options) { - return flushdb(options, null); - } - - /** - * Delete all keys from the database - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage flushdb(Options options, final ResponseListener listener) { - send("flushdb", new KuzzleJSONObject(), options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #geoadd(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage geoadd(String key, JSONObject[] points) { - return geoadd(key, points, null, null); - } - - /** - * {@link #geoadd(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage geoadd(String key, JSONObject[] points, final ResponseListener listener) { - return geoadd(key, points, null, listener); - } - - /** - * {@link #geoadd(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage geoadd(String key, JSONObject[] points, Options options) { - return geoadd(key, points, options, null); - } - - /** - * Add geospatial points to a key - * @param key Key ID - * @param points Geospatial points to add - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage geoadd(String key, JSONObject[] points, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("points", new JSONArray(Arrays.asList(points))) - ); - - send("geoadd", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #geodist(String, String, String, Options, ResponseListener)} - */ - public void geodist(String key, String member1, String member2, final ResponseListener listener) { - geodist(key, member1, member2, null, listener); - } - - /** - * Get the distance between two geospatial members of a key (see geoadd) - * @param key Key ID - * @param member1 Geospatial point 1 - * @param member2 Geospatial point 2 - * @param options Request options - * @param listener Response callback listener - */ - public void geodist(String key, String member1, String member2, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("member1", member1) - .put("member2", member2); - - if (options != null) { - if (options.getUnit() != null) { - query.put("unit", options.getUnit()); - } - } - - send("geodist", query, options, getCallbackDouble(listener)); - } - - /** - * {@link #geohash(String, String[], Options, ResponseListener)} - */ - public void geohash(String key, String[] members, final ResponseListener listener) { - geohash(key, members, null, listener); - } - - /** - * Return the geohash values for the provided key's members - * @param key Key ID - * @param members List of geospatial members - * @param options Request options - * @param listener Response callback listener - */ - public void geohash(String key, String[] members, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("members", new JSONArray(Arrays.asList(members))); - - send("geohash", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #geopos(String, String[], Options, ResponseListener)} - */ - public void geopos(String key, String[] members, final ResponseListener listener) { - geopos(key, members, null, listener); - } - - /** - * Return the longitude/latitude values for the provided key's members - * @param key Key ID - * @param members List of geospatial members - * @param options Request options - * @param listener Response callback listener - */ - public void geopos(String key, String[] members, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("members", new JSONArray(Arrays.asList(members))); - - send( - "geopos", - query, - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - /* - Converts the resulting array of arrays of strings, - into an array of arrays of doubles - */ - JSONArray raw = response.getJSONArray("result"); - Double[][] result = new Double[raw.length()][2]; - - for (int i = 0; i < raw.length(); i++) { - JSONArray rawPos = raw.getJSONArray(i); - - for (int j = 0; j < rawPos.length(); j++) { - result[i][j] = Double.parseDouble(rawPos.getString(j)); - } - } - - listener.onSuccess(result); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #georadius(String, double, double, double, String, Options, ResponseListener)} - */ - public void georadius(String key, double lon, double lat, double distance, String unit, final ResponseListener listener) { - georadius(key, lon, lat, distance, unit, null, listener); - } - - /** - * Return the geospatial members of a key inside the provided radius - * @param key Key ID - * @param lon Longitude value for the radius center - * @param lat Latitude value for the radius center - * @param distance Radius value - * @param unit Radius distance unit - * @param options Request options - * @param listener Response callback listener - */ - public void georadius(String key, double lon, double lat, double distance, String unit, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("lon", lon) - .put("lat", lat) - .put("distance", distance) - .put("unit", unit); - - assignGeoradiusOptions(query, options); - - send( - "georadius", - query, - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(mapGeoradiusResults(response.getJSONArray("result"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #georadiusbymember(String, String, double, String, Options, ResponseListener)} - */ - public void georadiusbymember(String key, String member, double distance, String unit, final ResponseListener listener) { - georadiusbymember(key, member, distance, unit, null, listener); - } - - /** - * Returns the members (added with geoadd) of a given key inside - * the provided geospatial radius, centered around one of a - * key's member. - * - * @param key Key ID - * @param member Geospatial member, center of the radius - * @param distance Radius value - * @param unit Radius distance unit - * @param options Request options - * @param listener Response callback listener - */ - public void georadiusbymember(String key, String member, double distance, String unit, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("member", member) - .put("distance", distance) - .put("unit", unit); - - assignGeoradiusOptions(query, options); - - send( - "georadiusbymember", - query, - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(mapGeoradiusResults(response.getJSONArray("result"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #get(String, Options, ResponseListener)} - */ - public void get(String key, final ResponseListener listener) { - get(key, null, listener); - } - - - /** - * Get a key's value - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - */ - public void get(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("get", query, options, getCallbackString(listener)); - } - - /** - * {@link #getbit(String, long, Options, ResponseListener)} - */ - public void getbit(String key, long offset, final ResponseListener listener) { - getbit(key, offset, null, listener); - } - - /** - * Returns the bit value at offset, in the string value stored in a key. - * @param key Key ID - * @param offset Offset value - * @param options Request options - * @param listener Response callback listener - */ - public void getbit(String key, long offset, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("offset", offset); - - send("getbit", query, options, getCallbackInt(listener)); - } - - /** - * {@link #getrange(String, long, long, Options, ResponseListener)} - */ - public void getrange(String key, long start, long end, final ResponseListener listener) { - getrange(key, start, end, null, listener); - } - - /** - * Returns a substring of a key's value (index starts at position 0). - * @param key Key ID - * @param start Substring starting position - * @param end Substring ending position - * @param options Request options - * @param listener Response callback listener - */ - public void getrange(String key, long start, long end, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("start", start) - .put("end", end); - - send("getrange", query, options, getCallbackString(listener)); - } - - /** - * {@link #getset(String, String, Options, ResponseListener)} - */ - public MemoryStorage getset(String key, String value) { - return getset(key, value, null, null); - } - - /** - * {@link #getset(String, String, Options, ResponseListener)} - */ - public MemoryStorage getset(String key, String value, final ResponseListener listener) { - return getset(key, value, null, listener); - } - - /** - * {@link #getset(String, String, Options, ResponseListener)} - */ - public MemoryStorage getset(String key, String value, Options options) { - return getset(key, value, options, null); - } - - /** - * Sets a new value for a key and returns its previous value. - * @param key Key ID - * @param value New value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage getset(String key, String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - ); - - send("getset", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #hdel(String, String[], Options, ResponseListener)} - */ - public MemoryStorage hdel(String key, String[] fields) { - return hdel(key, fields, null, null); - } - - /** - * {@link #hdel(String, String[], Options, ResponseListener)} - */ - public MemoryStorage hdel(String key, String[] fields, final ResponseListener listener) { - return hdel(key, fields, null, listener); - } - - /** - * {@link #hdel(String, String[], Options, ResponseListener)} - */ - public MemoryStorage hdel(String key, String[] fields, Options options) { - return hdel(key, fields, options, null); - } - - /** - * Remove fields from a hash - * @param key Hash key ID - * @param fields Fields to remove - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage hdel(String key, String[] fields, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("fields", new JSONArray(Arrays.asList(fields))) - ); - - send("hdel", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #hexists(String, String, Options, ResponseListener)} - */ - public void hexists(String key, String field, final ResponseListener listener) { - hexists(key, field, null, listener); - } - - /** - * Check if a field exists in a hash - * @param key Hash key ID - * @param field Field name - * @param options Request options - * @param listener Response callback listener - */ - public void hexists(String key, String field, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("field", field); - - send("hexists", query, options, getCallbackInt(listener)); - } - - /** - * {@link #hget(String, String, Options, ResponseListener)} - */ - public void hget(String key, String field, final ResponseListener listener) { - hget(key, field, null, listener); - } - - /** - * Return the field's value of a hash - * @param key Hash key ID - * @param field Field name - * @param options Request options - * @param listener Response callback listener - */ - public void hget(String key, String field, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("field", field); - - send("hget", query, options, getCallbackString(listener)); - } - - /** - * {@link #hgetall(String, Options, ResponseListener)} - */ - public void hgetall(String key, final ResponseListener listener) { - hgetall(key, null, listener); - } - - /** - * Return all fields and values of a hash - * @param key Hash key ID - * @param options Request options - * @param listener Response callback listener - */ - public void hgetall(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send( - "hgetall", - query, - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result")); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #hincrby(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage hincrby(String key, String field, long value) { - return hincrby(key, field, value, null, null); - } - - /** - * {@link #hincrby(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage hincrby(String key, String field, long value, final ResponseListener listener) { - return hincrby(key, field, value, null, listener); - } - - /** - * {@link #hincrby(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage hincrby(String key, String field, long value, Options options) { - return hincrby(key, field, value, options, null); - } - - /** - * Increments the number stored in a hash field by the provided integer value. - * @param key Hash Key ID - * @param field Field to increment - * @param value Increment value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage hincrby(String key, String field, long value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("field", field) - .put("value", value) - ); - - send("hincrby", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #hincrbyfloat(String, String, double, Options, ResponseListener)} - */ - public MemoryStorage hincrbyfloat(String key, String field, double value) { - return hincrbyfloat(key, field, value, null, null); - } - - /** - * {@link #hincrbyfloat(String, String, double, Options, ResponseListener)} - */ - public MemoryStorage hincrbyfloat(String key, String field, double value, final ResponseListener listener) { - return hincrbyfloat(key, field, value, null, listener); - } - - /** - * {@link #hincrbyfloat(String, String, double, Options, ResponseListener)} - */ - public MemoryStorage hincrbyfloat(String key, String field, double value, Options options) { - return hincrbyfloat(key, field, value, options, null); - } - - /** - * Increments the number stored in a hash field by the provided float value. - * @param key Hash key ID - * @param field Field to increment - * @param value Increment value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage hincrbyfloat(String key, String field, double value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("field", field) - .put("value", value) - ); - - send("hincrbyfloat", query, options, listener != null ? getCallbackDouble(listener) : null); - - return this; - } - - /** - * {@link #hkeys(String, Options, ResponseListener)} - */ - public void hkeys(String key, final ResponseListener listener) { - hkeys(key, null, listener); - } - - /** - * Return all the field names contained in a hash - * @param key Hash key ID - * @param options Request options - * @param listener Response callback listener - */ - public void hkeys(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("hkeys", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #hlen(String, Options, ResponseListener)} - */ - public void hlen(String key, final ResponseListener listener) { - hlen(key, null, listener); - } - - /** - * Return the number of members of a hash - * @param key Hash key ID - * @param options Request options - * @param listener Response callback listener - */ - public void hlen(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("hlen", query, options, getCallbackLong(listener)); - } - - /** - * {@link #hmget(String, String[], Options, ResponseListener)} - */ - public void hmget(String key, String[] fields, final ResponseListener listener) { - hmget(key, fields, null, listener); - } - - /** - * Returns the values of the specified hash’s fields. - * @param key Hash key ID - * @param fields Field names to return - * @param options Request options - * @param listener Response callback listener - */ - public void hmget(String key, String[] fields, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("fields", new JSONArray(Arrays.asList(fields))); - - send("hmget", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #hmset(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage hmset(String key, JSONObject[] entries) { - return hmset(key, entries, null, null); - } - - /** - * {@link #hmset(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage hmset(String key, JSONObject[] entries, final ResponseListener listener) { - return hmset(key, entries, null, listener); - } - - /** - * {@link #hmset(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage hmset(String key, JSONObject[] entries, Options options) { - return hmset(key, entries, options, null); - } - - /** - * Sets multiple fields at once in a hash. - * @param key Hash key ID - * @param entries Name-Value pairs to set - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage hmset(String key, JSONObject[] entries, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("entries", new JSONArray(Arrays.asList(entries))) - ); - - send("hmset", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #hscan(String, long, Options, ResponseListener)} - */ - public void hscan(String key, long cursor, final ResponseListener listener) { - hscan(key, cursor, null, listener); - } - - /** - * Identical to scan, except that hscan iterates the fields contained in a hash. - * @param key Hash key ID - * @param cursor Cursor position (0 to start a new scan) - * @param options Request options - * @param listener Response callback listener - */ - public void hscan(String key, long cursor, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("cursor", cursor); - - if (options != null) { - if (options.getCount() != null) { - query.put("count", options.getCount()); - } - - if (options.getMatch() != null) { - query.put("match", options.getMatch()); - } - } - - send("hscan", query, options, getCallbackScanResult(listener)); - } - - /** - * {@link #hset(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage hset(String key, String field, String value) { - return hset(key, field, value, null, null); - } - - /** - * {@link #hset(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage hset(String key, String field, String value, final ResponseListener listener) { - return hset(key, field, value, null, listener); - } - - /** - * {@link #hset(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage hset(String key, String field, String value, Options options) { - return hset(key, field, value, options, null); - } - - /** - * Sets a field and its value in a hash. - * If the key does not exist, a new key holding a hash is created. - * @param key Hash key ID - * @param field Field name to set - * @param value Value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage hset(String key, String field, String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("field", field) - .put("value", value) - ); - - send("hset", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #hsetnx(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage hsetnx(String key, String field, String value) { - return hsetnx(key, field, value, null, null); - } - - /** - * {@link #hsetnx(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage hsetnx(String key, String field, String value, final ResponseListener listener) { - return hsetnx(key, field, value, null, listener); - } - - /** - * {@link #hsetnx(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage hsetnx(String key, String field, String value, Options options) { - return hsetnx(key, field, value, options, null); - } - - /** - * Sets a field and its value in a hash, only if the field does not already exist. - * @param key Hash key ID - * @param field Field name to set - * @param value Value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage hsetnx(String key, String field, String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("field", field) - .put("value", value) - ); - - send("hsetnx", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #hstrlen(String, String, Options, ResponseListener)} - */ - public void hstrlen(String key, String field, final ResponseListener listener) { - hstrlen(key, field, null, listener); - } - - /** - * Returns the string length of a field’s value in a hash. - * @param key Hash key ID - * @param field Field name - * @param options Request options - * @param listener Response callback listener - */ - public void hstrlen(String key, String field, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("field", field); - - send("hstrlen", query, options, getCallbackLong(listener)); - } - - /** - * {@link #hvals(String, Options, ResponseListener)} - */ - public void hvals(String key, final ResponseListener listener) { - hvals(key, null, listener); - } - - /** - * Returns all values contained in a hash. - * @param key Hash key ID - * @param options Request options - * @param listener Response callback listener - */ - public void hvals(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("hvals", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #incr(String, Options, ResponseListener)} - */ - public MemoryStorage incr(String key) { - return incr(key, null, null); - } - - /** - * {@link #incr(String, Options, ResponseListener)} - */ - public MemoryStorage incr(String key, Options options) { - return incr(key, options, null); - } - - /** - * {@link #incr(String, Options, ResponseListener)} - */ - public MemoryStorage incr(String key, final ResponseListener listener) { - return incr(key, null, listener); - } - - /** - * Increments the number stored at key by 1. - * If the key does not exist, it is set to 0 before performing the operation. - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage incr(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("incr", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #incrby(String, long, Options, ResponseListener)} - */ - public MemoryStorage incrby(String key, long value) { - return incrby(key, value, null, null); - } - - /** - * {@link #incrby(String, long, Options, ResponseListener)} - */ - public MemoryStorage incrby(String key, long value, Options options) { - return incrby(key, value, options, null); - } - - /** - * {@link #incrby(String, long, Options, ResponseListener)} - */ - public MemoryStorage incrby(String key, long value, final ResponseListener listener) { - return incrby(key, value, null, listener); - } - - /** - * Increments the number stored at key by the provided integer value. - * If the key does not exist, it is set to 0 before performing the operation. - * @param key Key ID - * @param value Increment value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage incrby(String key, long value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - ); - - send("incrby", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #incrbyfloat(String, double, Options, ResponseListener)} - */ - public MemoryStorage incrbyfloat(String key, double value) { - return incrbyfloat(key, value, null, null); - } - - /** - * {@link #incrbyfloat(String, double, Options, ResponseListener)} - */ - public MemoryStorage incrbyfloat(String key, double value, final ResponseListener listener) { - return incrbyfloat(key, value, null, listener); - } - - /** - * {@link #incrbyfloat(String, double, Options, ResponseListener)} - */ - public MemoryStorage incrbyfloat(String key, double value, Options options) { - return incrbyfloat(key, value, options, null); - } - - /** - * Increments the number stored at key by the provided float value. - * If the key does not exist, it is set to 0 before performing the operation. - * @param key Key ID - * @param value Increment value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage incrbyfloat(String key, double value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - ); - - send("incrbyfloat", query, options, listener != null ? getCallbackDouble(listener) : null); - - return this; - } - - /** - * {@link #keys(String, Options, ResponseListener)} - */ - public void keys(String pattern, final ResponseListener listener) { - keys(pattern, null, listener); - } - - /** - * Returns all keys matching the provided pattern. - * @param pattern Match pattern - * @param options Request options - * @param listener Response callback listener - */ - public void keys(String pattern, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("pattern", pattern); - - send("keys", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #lindex(String, long, Options, ResponseListener)} - */ - public void lindex(String key, long index, final ResponseListener listener) { - lindex(key, index, null, listener); - } - - /** - * Returns the element at the provided index in a list. - * @param key List ID - * @param index Index position - * @param options [description] - * @param listener Response callback listener - */ - public void lindex(String key, long index, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("index", index); - - send("lindex", query, options, getCallbackString(listener)); - } - - /** - * {@link #linsert(String, String, String, String, Options, ResponseListener)} - */ - public MemoryStorage linsert(String key, String position, String pivot, String value) { - return linsert(key, position, pivot, value, null, null); - } - - /** - * {@link #linsert(String, String, String, String, Options, ResponseListener)} - */ - public MemoryStorage linsert(String key, String position, String pivot, String value, final ResponseListener listener) { - return linsert(key, position, pivot, value, null, listener); - } - - /** - * {@link #linsert(String, String, String, String, Options, ResponseListener)} - */ - public MemoryStorage linsert(String key, String position, String pivot, String value, Options options) { - return linsert(key, position, pivot, value, options, null); - } - - - /** - * Inserts a value in a list, either before or after the reference pivot value. - * @param key List ID - * @param position Either "after" or "before" - * @param pivot Pivot value in the list - * @param value Value to insert - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage linsert(String key, String position, String pivot, String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("position", position) - .put("pivot", pivot) - .put("value", value) - ); - - send("linsert", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #llen(String, Options, ResponseListener)} - */ - public void llen(String key, final ResponseListener listener) { - llen(key, null, listener); - } - - /** - * Counts the number of items in a list. - * @param key List ID - * @param options Request options - * @param listener Response callback listener - */ - public void llen(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("llen", query, options, getCallbackLong(listener)); - } - - /** - * {@link #lpop(String, Options, ResponseListener)} - */ - public MemoryStorage lpop(String key) { - return lpop(key, null, null); - } - - /** - * {@link #lpop(String, Options, ResponseListener)} - */ - public MemoryStorage lpop(String key, final ResponseListener listener) { - return lpop(key, null, listener); - } - - /** - * {@link #lpop(String, Options, ResponseListener)} - */ - public MemoryStorage lpop(String key, Options options) { - return lpop(key, options, null); - } - - /** - * Removes and returns the first element of a list. - * @param key List ID - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage lpop(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("lpop", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #lpush(String, String[], Options, ResponseListener)} - */ - public MemoryStorage lpush(String key, String[] values) { - return lpush(key, values, null, null); - } - - /** - * {@link #lpush(String, String[], Options, ResponseListener)} - */ - public MemoryStorage lpush(String key, String[] values, final ResponseListener listener) { - return lpush(key, values, null, listener); - } - - /** - * {@link #lpush(String, String[], Options, ResponseListener)} - */ - public MemoryStorage lpush(String key, String[] values, Options options) { - return lpush(key, values, options, null); - } - - /** - * Prepends the specified values to a list. - * If the key does not exist, it is created holding - * an empty list before performing the operation. - * @param key List ID - * @param values Values to prepend - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage lpush(String key, String[] values, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("values", new JSONArray(Arrays.asList(values))) - ); - - send("lpush", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #lpushx(String, String, Options, ResponseListener)} - */ - public MemoryStorage lpushx(String key, final String value) { - return lpushx(key, value, null, null); - } - - /** - * {@link #lpushx(String, String, Options, ResponseListener)} - */ - public MemoryStorage lpushx(String key, final String value, Options options) { - return lpushx(key, value, options, null); - } - - /** - * {@link #lpushx(String, String, Options, ResponseListener)} - */ - public MemoryStorage lpushx(String key, final String value, final ResponseListener listener) { - return lpushx(key, value, null, listener); - } - - /** - * Prepends the specified value to a list, - * only if the key already exists and if it holds a list. - * @param key List ID - * @param value Value to prepend - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage lpushx(String key, final String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - ); - - send("lpushx", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #lrange(String, long, long, Options, ResponseListener)} - */ - public void lrange(String key, long start, long stop, final ResponseListener listener) { - lrange(key, start, stop, null, listener); - } - - /** - * Returns the list elements between the start and stop positions (inclusive). - * @param key List ID - * @param start Start position - * @param stop End position - * @param options Request options - * @param listener Response callback listener - */ - public void lrange(String key, long start, long stop, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("start", start) - .put("stop", stop); - - send("lrange", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #lrem(String, long, String, Options, ResponseListener)} - */ - public MemoryStorage lrem(String key, long count, String value) { - return lrem(key, count, value, null, null); - } - - /** - * {@link #lrem(String, long, String, Options, ResponseListener)} - */ - public MemoryStorage lrem(String key, long count, String value, final ResponseListener listener) { - return lrem(key, count, value, null, listener); - } - - /** - * {@link #lrem(String, long, String, Options, ResponseListener)} - */ - public MemoryStorage lrem(String key, long count, String value, Options options) { - return lrem(key, count, value, options, null); - } - - /** - * Removes the first count occurences of elements equal to value from a list. - * @param key List ID - * @param count Number of elements to remove - * @param value Value to remove - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage lrem(String key, long count, String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("count", count) - .put("value", value) - ); - - send("lrem", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #lset(String, long, String, Options, ResponseListener)} - */ - public MemoryStorage lset(String key, long index, String value) { - return lset(key, index, value, null, null); - } - - /** - * {@link #lset(String, long, String, Options, ResponseListener)} - */ - public MemoryStorage lset(String key, long index, String value, final ResponseListener listener) { - return lset(key, index, value, null, listener); - } - - /** - * {@link #lset(String, long, String, Options, ResponseListener)} - */ - public MemoryStorage lset(String key, long index, String value, Options options) { - return lset(key, index, value, options, null); - } - - /** - * Sets the list element at index with the provided value. - * @param key List ID - * @param index Index of the element to set - * @param value Element new value - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage lset(String key, long index, String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("index", index) - .put("value", value) - ); - - send("lset", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #ltrim(String, long, long, Options, ResponseListener)} - */ - public MemoryStorage ltrim(String key, long start, long stop) { - return ltrim(key, start, stop, null, null); - } - - /** - * {@link #ltrim(String, long, long, Options, ResponseListener)} - */ - public MemoryStorage ltrim(String key, long start, long stop, final ResponseListener listener) { - return ltrim(key, start, stop, null, listener); - } - - /** - * {@link #ltrim(String, long, long, Options, ResponseListener)} - */ - public MemoryStorage ltrim(String key, long start, long stop, Options options) { - return ltrim(key, start, stop, options, null); - } - - /** - * Trims an existing list so that it will - * contain only the specified range of elements specified. - * @param key List ID - * @param start Start position - * @param stop End position - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage ltrim(String key, long start, long stop, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("start", start) - .put("stop", stop) - ); - - send("ltrim", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #mget(String[], Options, ResponseListener)} - */ - public void mget(String[] keys, final ResponseListener listener) { - mget(keys, null, listener); - } - - /** - * Returns the values of the provided keys. - * @param keys List of key identifiers - * @param options Request options - * @param listener Response callback listener - */ - public void mget(String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys))); - - send("mget", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #mset(JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage mset(JSONObject[] entries) { - return mset(entries, null, null); - } - - /** - * {@link #mset(JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage mset(JSONObject[] entries, Options options) { - return mset(entries, options, null); - } - - /** - * {@link #mset(JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage mset(JSONObject[] entries, final ResponseListener listener) { - return mset(entries, null, listener); - } - - /** - * Sets the provided keys to their respective values. - * If a key does not exist, it is created. Otherwise, the key’s value is overwritten. - * @param entries Key-Value pairs - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage mset(JSONObject[] entries, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("body", new KuzzleJSONObject().put("entries", new JSONArray(Arrays.asList(entries)))); - - send("mset", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #msetnx(JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage msetnx(JSONObject[] entries) { - return msetnx(entries, null, null); - } - - /** - * {@link #msetnx(JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage msetnx(JSONObject[] entries, Options options) { - return msetnx(entries, options, null); - } - - /** - * {@link #msetnx(JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage msetnx(JSONObject[] entries, final ResponseListener listener) { - return msetnx(entries, null, listener); - } - - /** - * Sets the provided keys to their respective values, only if they do not exist. - * If a key exists, then the whole operation is aborted and no key is set - * @param entries Key-Value pairs to set - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage msetnx(JSONObject[] entries, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("body", new KuzzleJSONObject().put("entries", new JSONArray(Arrays.asList(entries)))); - - send("msetnx", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #object(String, String, Options, ResponseListener)} - */ - public void object(String key, String subcommand, final ResponseListener listener) { - object(key, subcommand, null, listener); - } - - /** - * Inspects the low-level properties of a key. - * @param key Key ID - * @param subcommand Name of the low-level property to get - * @param options Request options - * @param listener Response callback listener - */ - public void object(String key, String subcommand, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("subcommand", subcommand); - - send("object", query, options, getCallbackString(listener)); - } - - /** - * {@link #persist(String, Options, ResponseListener)} - */ - public MemoryStorage persist(String key) { - return persist(key, null, null); - } - - /** - * {@link #persist(String, Options, ResponseListener)} - */ - public MemoryStorage persist(String key, final ResponseListener listener) { - return persist(key, null, listener); - } - - /** - * {@link #persist(String, Options, ResponseListener)} - */ - public MemoryStorage persist(String key, Options options) { - return persist(key, options, null); - } - - /** - * Removes the expiration delay or timestamp from a key, making it persistent. - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage persist(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("persist", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #pexpire(String, long, Options, ResponseListener)} - */ - public MemoryStorage pexpire(String key, long milliseconds) { - return pexpire(key, milliseconds, null, null); - } - - /** - * {@link #pexpire(String, long, Options, ResponseListener)} - */ - public MemoryStorage pexpire(String key, long milliseconds, Options options) { - return pexpire(key, milliseconds, options, null); - } - - /** - * {@link #pexpire(String, long, Options, ResponseListener)} - */ - public MemoryStorage pexpire(String key, long milliseconds, final ResponseListener listener) { - return pexpire(key, milliseconds, null, listener); - } - - /** - * Sets a timeout (in milliseconds) on a key. - * After the timeout has expired, the key will automatically be deleted. - * @param key Key ID - * @param milliseconds Expiration time in milliseconds - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage pexpire(String key, long milliseconds, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("milliseconds", milliseconds) - ); - - send("pexpire", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #pexpireat(String, long, Options, ResponseListener)} - */ - public MemoryStorage pexpireat(String key, long timestamp) { - return pexpireat(key, timestamp, null, null); - } - - /** - * {@link #pexpireat(String, long, Options, ResponseListener)} - */ - public MemoryStorage pexpireat(String key, long timestamp, Options options) { - return pexpireat(key, timestamp, options, null); - } - - /** - * {@link #pexpireat(String, long, Options, ResponseListener)} - */ - public MemoryStorage pexpireat(String key, long timestamp, final ResponseListener listener) { - return pexpireat(key, timestamp, null, listener); - } - - /** - * Sets an expiration timestamp on a key. - * After the timestamp has been reached, the key will automatically be deleted. - * @param key Key ID - * @param timestamp Expiration timestamp (Epoch-time in milliseconds) - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage pexpireat(String key, long timestamp, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("timestamp", timestamp) - ); - - send("pexpireat", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #pfadd(String, String[], Options, ResponseListener)} - */ - public MemoryStorage pfadd(String key, String[] elements) { - return pfadd(key, elements, null, null); - } - - /** - * {@link #pfadd(String, String[], Options, ResponseListener)} - */ - public MemoryStorage pfadd(String key, String[] elements, final ResponseListener listener) { - return pfadd(key, elements, null, listener); - } - - /** - * {@link #pfadd(String, String[], Options, ResponseListener)} - */ - public MemoryStorage pfadd(String key, String[] elements, Options options) { - return pfadd(key, elements, options, null); - } - - /** - * Adds elements to an HyperLogLog data structure. - * @param key HyperLogLog ID - * @param elements Array of elements to add - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage pfadd(String key, String[] elements, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("elements", new JSONArray(Arrays.asList(elements))) - ); - - send("pfadd", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #pfcount(String[], Options, ResponseListener)} - */ - public void pfcount(String[] keys, final ResponseListener listener) { - pfcount(keys, null, listener); - } - - /** - * Returns the probabilistic cardinality of a HyperLogLog data structure, - * or of the merged HyperLogLog structures if more than 1 is provided (see pfadd). - * @param keys HyperLogLog ID - * @param options Request options - * @param listener Response callback listener - */ - public void pfcount(String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys))); - - send("pfcount", query, options, getCallbackLong(listener)); - } - - /** - * {@link #pfmerge(String, String[], Options, ResponseListener)} - */ - public MemoryStorage pfmerge(String key, String[] sources) { - return pfmerge(key, sources, null, null); - } - - /** - * {@link #pfmerge(String, String[], Options, ResponseListener)} - */ - public MemoryStorage pfmerge(String key, String[] sources, final ResponseListener listener) { - return pfmerge(key, sources, null, listener); - } - - /** - * {@link #pfmerge(String, String[], Options, ResponseListener)} - */ - public MemoryStorage pfmerge(String key, String[] sources, Options options) { - return pfmerge(key, sources, options, null); - } - - /** - * Merges multiple HyperLogLog data structures into an unique HyperLogLog structure - * stored at key, approximating the cardinality of the union of the source structures. - * @param key Destination key ID - * @param sources Array of HyperLogLog ID to merge - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage pfmerge(String key, String[] sources, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("sources", new JSONArray(Arrays.asList(sources))) - ); - - send("pfmerge", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #ping(Options, ResponseListener)} - */ - public void ping(final ResponseListener listener) { - ping(null, listener); - } - - /** - * Pings the memory storage database. - * @param options Request options - * @param listener Response callback listener - */ - public void ping(Options options, final ResponseListener listener) { - send("ping", new KuzzleJSONObject(), options, getCallbackString(listener)); - } - - /** - * {@link #psetex(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage psetex(String key, String value, long milliseconds) { - return psetex(key, value, milliseconds, null, null); - } - - /** - * {@link #psetex(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage psetex(String key, String value, long milliseconds, final ResponseListener listener) { - return psetex(key, value, milliseconds, null, listener); - } - - /** - * {@link #psetex(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage psetex(String key, String value, long milliseconds, Options options) { - return psetex(key, value, milliseconds, options, null); - } - - /** - * Sets a key with the provided value, and an expiration delay - * expressed in milliseconds. If the key does not exist, it is created beforehand. - * @param key Key ID - * @param value Value to set - * @param milliseconds Expiration delay in milliseconds - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage psetex(String key, String value, long milliseconds, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - .put("milliseconds", milliseconds) - ); - - send("psetex", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #pttl(String, Options, ResponseListener)} - */ - public void pttl(String key, final ResponseListener listener) { - pttl(key, null, listener); - } - - /** - * Returns the remaining time to live of a key, in milliseconds. - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - */ - public void pttl(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("pttl", query, options, getCallbackLong(listener)); - } - - /** - * {@link #randomkey(Options, ResponseListener)} - */ - public void randomkey(final ResponseListener listener) { - randomkey(null, listener); - } - - /** - * Returns a random key from the memory storage. - * @param options Request options - * @param listener Response callback listener - */ - public void randomkey(Options options, final ResponseListener listener) { - send("randomkey", new KuzzleJSONObject(), options, getCallbackString(listener)); - } - - /** - * {@link #rename(String, String, Options, ResponseListener)} - */ - public MemoryStorage rename(String key, String newkey) { - return rename(key, newkey, null, null); - } - - /** - * {@link #rename(String, String, Options, ResponseListener)} - */ - public MemoryStorage rename(String key, String newkey, final ResponseListener listener) { - return rename(key, newkey, null, listener); - } - - /** - * {@link #rename(String, String, Options, ResponseListener)} - */ - public MemoryStorage rename(String key, String newkey, Options options) { - return rename(key, newkey, options, null); - } - - /** - * Renames a key to newkey. If newkey already exists, it is overwritten. - * @param key Key ID - * @param newkey New key ID - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage rename(String key, String newkey, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("newkey", newkey) - ); - - send("rename", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #renamenx(String, String, Options, ResponseListener)} - */ - public MemoryStorage renamenx(String key, String newkey) { - return renamenx(key, newkey, null, null); - } - - /** - * {@link #renamenx(String, String, Options, ResponseListener)} - */ - public MemoryStorage renamenx(String key, String newkey, final ResponseListener listener) { - return renamenx(key, newkey, null, listener); - } - - /** - * {@link #renamenx(String, String, Options, ResponseListener)} - */ - public MemoryStorage renamenx(String key, String newkey, Options options) { - return renamenx(key, newkey, options, null); - } - - /** - * Renames a key to newkey, only if newkey does not already exist. - * @param key Key ID - * @param newkey New key ID - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage renamenx(String key, String newkey, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("newkey", newkey) - ); - - send("renamenx", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #rpop(String, Options, ResponseListener)} - */ - public MemoryStorage rpop(String key) { - return rpop(key, null, null); - } - - /** - * {@link #rpop(String, Options, ResponseListener)} - */ - public MemoryStorage rpop(String key, final ResponseListener listener) { - return rpop(key, null, listener); - } - - /** - * {@link #rpop(String, Options, ResponseListener)} - */ - public MemoryStorage rpop(String key, Options options) { - return rpop(key, options, null); - } - - /** - * Removes and returns the last element of a list. - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public MemoryStorage rpop(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("rpop", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #rpoplpush(String, String, Options, ResponseListener)} - */ - public MemoryStorage rpoplpush(String source, String destination) { - return rpoplpush(source, destination, null, null); - } - - /** - * {@link #rpoplpush(String, String, Options, ResponseListener)} - */ - public MemoryStorage rpoplpush(String source, String destination, final ResponseListener listener) { - return rpoplpush(source, destination, null, listener); - } - - /** - * {@link #rpoplpush(String, String, Options, ResponseListener)} - */ - public MemoryStorage rpoplpush(String source, String destination, Options options) { - return rpoplpush(source, destination, options, null); - } - - /** - * Removes the last element of the list at source and - * pushes it back at the start of the list at destination. - * @param source Source key ID - * @param destination Destination key ID - * @param options [description] - * @param listener [description] - * @return [description] - */ - public MemoryStorage rpoplpush(String source, String destination, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("body", new KuzzleJSONObject() - .put("source", source) - .put("destination", destination) - ); - - send("rpoplpush", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #rpush(String, String[], Options, ResponseListener)} - */ - public MemoryStorage rpush(String key, String[] values) { - return rpush(key, values, null, null); - } - - /** - * {@link #rpush(String, String[], Options, ResponseListener)} - */ - public MemoryStorage rpush(String key, String[] values, final ResponseListener listener) { - return rpush(key, values, null, listener); - } - - /** - * {@link #rpush(String, String[], Options, ResponseListener)} - */ - public MemoryStorage rpush(String key, String[] values, Options options) { - return rpush(key, values, options, null); - } - - /** - * Appends the specified values at the end of a list. - * If the key does not exist, it is created holding an empty - * list before performing the operation. - * @param key List ID - * @param values Values to append - * @param options [description] - * @param listener [description] - * @return [description] - */ - public MemoryStorage rpush(String key, String[] values, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("values", new JSONArray(Arrays.asList(values))) - ); - - send("rpush", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #rpushx(String, String, Options, ResponseListener)} - */ - public MemoryStorage rpushx(String key, final String value) { - return rpushx(key, value, null, null); - } - - /** - * {@link #rpushx(String, String, Options, ResponseListener)} - */ - public MemoryStorage rpushx(String key, final String value, Options options) { - return rpushx(key, value, options, null); - } - - /** - * {@link #rpushx(String, String, Options, ResponseListener)} - */ - public MemoryStorage rpushx(String key, final String value, final ResponseListener listener) { - return rpushx(key, value, null, listener); - } - - /** - * Appends the specified value at the end of a list, - * only if the key already exists and if it holds a list. - * @param key List ID - * @param value Value to append - * @param options [description] - * @param listener [description] - * @return [description] - */ - public MemoryStorage rpushx(String key, final String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - ); - - send("rpushx", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #sadd(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sadd(String key, String[] members) { - return sadd(key, members, null, null); - } - - /** - * {@link #sadd(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sadd(String key, String[] members, final ResponseListener listener) { - return sadd(key, members, null, listener); - } - - /** - * {@link #sadd(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sadd(String key, String[] members, Options options) { - return sadd(key, members, options, null); - } - - /** - * Adds members to a set of unique values stored at key. - * If the key does not exist, it is created beforehand. - * @param key Set ID - * @param members Members to add - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage sadd(String key, String[] members, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("members", new JSONArray(Arrays.asList(members))) - ); - - send("sadd", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #scan(long, Options, ResponseListener)} - */ - public void scan(long cursor, final ResponseListener listener) { - scan(cursor, null, listener); - } - - /** - * Iterates incrementally the set of keys in the database using a cursor. - * - * @param cursor Cursor position (0 to start an iteration) - * @param options Request options - * @param listener Response callback listener - */ - public void scan(long cursor, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("cursor", cursor); - - if (options != null) { - if (options.getCount() != null) { - query.put("count", options.getCount()); - } - - if (options.getMatch() != null) { - query.put("match", options.getMatch()); - } - } - - send("scan", query, options, getCallbackScanResult(listener)); - } - - /** - * {@link #scard(String, Options, ResponseListener)} - */ - public void scard(String key, final ResponseListener listener) { - scard(key, null, listener); - } - - /** - * Returns the number of members stored in a set of unique values. - * @param key Set ID - * @param options Request options - * @param listener Response callback listener - */ - public void scard(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("scard", query, options, getCallbackLong(listener)); - } - - /** - * {@link #sdiff(String, String[], Options, ResponseListener)} - */ - public void sdiff(String key, String[] keys, final ResponseListener listener) { - sdiff(key, keys, null, listener); - } - - /** - * Returns the difference between the set of unique - * values stored at key and the other provided sets. - * @param key Reference set ID - * @param keys Set IDs to compare - * @param options Request options - * @param listener Response callback listener - */ - public void sdiff(String key, String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("keys", new JSONArray(Arrays.asList(keys))); - - send("sdiff", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #sdiffstore(String, String[], String, Options, ResponseListener)} - */ - public MemoryStorage sdiffstore(String key, String[] keys, String destination) { - return sdiffstore(key, keys, destination, null, null); - } - - /** - * {@link #sdiffstore(String, String[], String, Options, ResponseListener)} - */ - public MemoryStorage sdiffstore(String key, String[] keys, String destination, final ResponseListener listener) { - return sdiffstore(key, keys, destination, null, listener); - } - - /** - * {@link #sdiffstore(String, String[], String, Options, ResponseListener)} - */ - public MemoryStorage sdiffstore(String key, String[] keys, String destination, Options options) { - return sdiffstore(key, keys, destination, options, null); - } - - /** - * Computes the difference between the set of unique values stored at key and - * the other provided sets, and stores the result in the key stored at destination. - * @param key Reference set ID - * @param keys Set IDs to compare - * @param destination Destination set ID - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage sdiffstore(String key, String[] keys, String destination, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("destination", destination) - .put("keys", new JSONArray(Arrays.asList(keys))) - ); - - send("sdiffstore", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #set(String, String, Options, ResponseListener)} - */ - public MemoryStorage set(String key, String value) { - return set(key, value, null, null); - } - - /** - * {@link #set(String, String, Options, ResponseListener)} - */ - public MemoryStorage set(String key, String value, final ResponseListener listener) { - return set(key, value, null, listener); - } - - /** - * {@link #set(String, String, Options, ResponseListener)} - */ - public MemoryStorage set(String key, String value, Options options) { - return set(key, value, options, null); - } - - /** - * Creates a key holding the provided value, or overwrites it if it already exists. - * @param key Key ID - * @param value Value to set - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage set(String key, String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - KuzzleJSONObject body = new KuzzleJSONObject().put("value", value); - - if (options != null) { - if (options.getEx() != null) { - body.put("ex", options.getEx()); - } - - if (options.getPx() != null) { - body.put("px", options.getPx()); - } - - body.put("nx", options.getNx()); - body.put("xx", options.getXx()); - } - - query.put("body", body); - - send("set", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #setex(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage setex(String key, String value, long seconds) { - return setex(key, value, seconds, null, null); - } - - /** - * {@link #setex(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage setex(String key, String value, long seconds, final ResponseListener listener) { - return setex(key, value, seconds, null, listener); - } - - /** - * {@link #setex(String, String, long, Options, ResponseListener)} - */ - public MemoryStorage setex(String key, String value, long seconds, Options options) { - return setex(key, value, seconds, options, null); - } - - /** - * Sets a key with the provided value, and an expiration delay - * expressed in seconds. If the key does not exist, it is created beforehand. - * @param key Key ID - * @param value Value to set - * @param seconds Expiration delay, in seconds - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage setex(String key, String value, long seconds, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - .put("seconds", seconds) - ); - - send("setex", query, options, listener != null ? getCallbackString(listener) : null); - - return this; - } - - /** - * {@link #setnx(String, String, Options, ResponseListener)} - */ - public MemoryStorage setnx(String key, String value) { - return setnx(key, value, null, null); - } - - /** - * {@link #setnx(String, String, Options, ResponseListener)} - */ - public MemoryStorage setnx(String key, String value, final ResponseListener listener) { - return setnx(key, value, null, listener); - } - - /** - * {@link #setnx(String, String, Options, ResponseListener)} - */ - public MemoryStorage setnx(String key, String value, Options options) { - return setnx(key, value, options, null); - } - - /** - * Sets a value on a key, only if it does not already exist. - * @param key Key ID - * @param value Value to set - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage setnx(String key, String value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("value", value) - ); - - send("setnx", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #sinter(String[], Options, ResponseListener)} - */ - public void sinter(String[] keys, final ResponseListener listener) { - sinter(keys, null, listener); - } - - /** - * Returns the intersection of the provided sets of unique values. - * @param keys Array of set IDs to intersect - * @param options Request options - * @param listener Response callback listener - */ - public void sinter(String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys))); - - send("sinter", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #sinterstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sinterstore(String destination, String[] keys) { - return sinterstore(destination, keys, null, null); - } - - /** - * {@link #sinterstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sinterstore(String destination, String[] keys, final ResponseListener listener) { - return sinterstore(destination, keys, null, listener); - } - - /** - * {@link #sinterstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sinterstore(String destination, String[] keys, Options options) { - return sinterstore(destination, keys, options, null); - } - - /** - * Computes the intersection of the provided sets of unique values - * and stores the result in the destination key. - * @param destination Destination key ID - * @param keys Array of set IDs to intersect - * @param options [description] - * @param listener [description] - * @return [description] - */ - public MemoryStorage sinterstore(String destination, String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("body", new KuzzleJSONObject() - .put("destination", destination) - .put("keys", new JSONArray(Arrays.asList(keys))) - ); - - send("sinterstore", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #sismember(String, String, Options, ResponseListener)} - */ - public void sismember(String key, String member, final ResponseListener listener) { - sismember(key, member, null, listener); - } - - /** - * Checks if member is a member of the set of unique values stored at key. - * @param key Set ID - * @param member Member name - * @param options Request options - * @param listener Response callback listener - */ - public void sismember(String key, String member, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("member", member); - - send("sismember", query, options, getCallbackInt(listener)); - } - - /** - * {@link #smembers(String, Options, ResponseListener)} - */ - public void smembers(String key, final ResponseListener listener) { - smembers(key, null, listener); - } - - /** - * Returns the members of a set of unique values. - * @param key Set ID - * @param options Request options - * @param listener Response callback listener - */ - public void smembers(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("smembers", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #smove(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage smove(String key, String destination, String member) { - return smove(key, destination, member, null, null); - } - - /** - * {@link #smove(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage smove(String key, String destination, String member, final ResponseListener listener) { - return smove(key, destination, member, null, listener); - } - - /** - * {@link #smove(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage smove(String key, String destination, String member, Options options) { - return smove(key, destination, member, options, null); - } - - /** - * Moves a member from a set of unique values to another. - * @param key Source set ID - * @param destination Destination set ID - * @param member Member to move - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage smove(String key, String destination, String member, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("destination", destination) - .put("member", member) - ); - - send("smove", query, options, listener != null ? getCallbackInt(listener) : null); - - return this; - } - - /** - * {@link #sort(String, Options, ResponseListener)} - */ - public void sort(String key, final ResponseListener listener) { - sort(key, null, listener); - } - - /** - * Sorts and returns elements contained in a list, a set of unique values or a - * sorted set. By default, sorting is numeric and elements are compared by their - * value interpreted as double precision floating point number. - * @param key ID of the key to sort - * @param options Request options - * @param listener Response callback listener - */ - public void sort(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - if (options != null) { - if (options.getBy() != null) { - query.put("by", options.getBy()); - } - - if (options.getDirection() != null) { - query.put("direction", options.getDirection()); - } - - if (options.getGet() != null) { - query.put("get", new JSONArray(Arrays.asList(options.getGet()))); - } - - if (options.getLimit() != null) { - query.put("limit", new JSONArray(Arrays.asList(options.getLimit()))); - } - - query.put("alpha", options.getAlpha()); - } - - send("sort", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #spop(String, Options, ResponseListener)} - */ - public MemoryStorage spop(String key) { - return spop(key, null, null); - } - - /** - * {@link #spop(String, Options, ResponseListener)} - */ - public MemoryStorage spop(String key, final ResponseListener listener) { - return spop(key, null, listener); - } - - /** - * {@link #spop(String, Options, ResponseListener)} - */ - public MemoryStorage spop(String key, Options options) { - return spop(key, options, null); - } - - /** - * Removes and returns one or more elements at random from a set of unique values. - * @param key Set ID - * @param listener [description] - * @return this - */ - public MemoryStorage spop(String key, Options options, final ResponseListener listener) { - ResponseListener callback = null; - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - if (options != null && options.getCount() != null) { - query.put("body", new KuzzleJSONObject().put("count", options.getCount())); - } - - if (listener != null) { - callback = new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (response.get("result") instanceof String) { - listener.onSuccess(new String[]{response.getString("result")}); - } - else { - JSONArray arr = response.getJSONArray("result"); - String[] elements = new String[arr.length()]; - - for (int i = 0; i < arr.length(); i++) { - elements[i] = arr.getString(i); - } - - listener.onSuccess(elements); - } - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }; - } - - send("spop", query, options, callback); - - return this; - } - - /** - * {@link #srandmember(String, Options, ResponseListener)} - */ - public MemoryStorage srandmember(String key, final ResponseListener listener) { - return srandmember(key, null, listener); - } - - /** - * Returns one or more members of a set of unique values, at random. - * @param key Set ID - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage srandmember(String key, Options options, final ResponseListener listener) { - ResponseListener callback = null; - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - if (options != null && options.getCount() != null) { - query.put("count", options.getCount()); - } - - if (listener != null) { - callback = new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (response.get("result") instanceof String) { - listener.onSuccess(new String[]{response.getString("result")}); - } - else { - JSONArray arr = response.getJSONArray("result"); - String[] elements = new String[arr.length()]; - - for (int i = 0; i < arr.length(); i++) { - elements[i] = arr.getString(i); - } - - listener.onSuccess(elements); - } - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }; - } - - send("srandmember", query, options, callback); - - return this; - } - - /** - * {@link #srem(String, String[], Options, ResponseListener)} - */ - public MemoryStorage srem(String key, String[] members) { - return srem(key, members, null, null); - } - - /** - * {@link #srem(String, String[], Options, ResponseListener)} - */ - public MemoryStorage srem(String key, String[] members, final ResponseListener listener) { - return srem(key, members, null, listener); - } - - /** - * {@link #srem(String, String[], Options, ResponseListener)} - */ - public MemoryStorage srem(String key, String[] members, Options options) { - return srem(key, members, options, null); - } - - /** - * Removes members from a set of unique values. - * @param key Set ID - * @param members Members to remove - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage srem(String key, String[] members, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("members", new JSONArray(Arrays.asList(members))) - ); - - send("srem", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #sscan(String, long, Options, ResponseListener)} - */ - public void sscan(String key, long cursor, final ResponseListener listener) { - sscan(key, cursor, null, listener); - } - - /** - * Identical to scan, except that sscan iterates the members contained in a set - * @param key Set ID - * @param cursor Cursor position (0 to start a new scan) - * @param options Request options - * @param listener Response callback listener - */ - public void sscan(String key, long cursor, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("cursor", cursor); - - if (options != null) { - if (options.getCount() != null) { - query.put("count", options.getCount()); - } - - if (options.getMatch() != null) { - query.put("match", options.getMatch()); - } - } - - send("sscan", query, options, getCallbackScanResult(listener)); - } - - /** - * {@link #strlen(String, Options, ResponseListener)} - */ - public void strlen(String key, final ResponseListener listener) { - strlen(key, null, listener); - } - - /** - * Returns the length of a value stored at key. - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - */ - public void strlen(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("strlen", query, options, getCallbackLong(listener)); - } - - /** - * {@link #sunion(String[], Options, ResponseListener)} - */ - public void sunion(String[] keys, final ResponseListener listener) { - sunion(keys, null, listener); - } - - /** - * Returns the union of the provided sets of unique values. - * @param keys Set IDs - * @param options Request options - * @param listener Response callback listener - */ - public void sunion(String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys))); - - send("sunion", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #sunionstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sunionstore(String destination, String[] keys) { - return sunionstore(destination, keys, null, null); - } - - /** - * {@link #sunionstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sunionstore(String destination, String[] keys, final ResponseListener listener) { - return sunionstore(destination, keys, null, listener); - } - - /** - * {@link #sunionstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage sunionstore(String destination, String[] keys, Options options) { - return sunionstore(destination, keys, options, null); - } - - /** - * Computes the union of the provided sets of unique values - * and stores the result in the destination key. - * @param destination Destination set ID - * @param keys Array of set IDs - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage sunionstore(String destination, String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("body", new KuzzleJSONObject() - .put("destination", destination) - .put("keys", new JSONArray(Arrays.asList(keys))) - ); - - send("sunionstore", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #time(Options, ResponseListener)} - */ - public void time(final ResponseListener listener) { - time(null, listener); - } - - /** - * Returns the current server time. - * @param options Request options - * @param listener Response callback listener - */ - public void time(Options options, final ResponseListener listener) { - send( - "time", - new KuzzleJSONObject(), - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONArray raw = response.getJSONArray("result"); - listener.onSuccess(new Long[]{ - Long.parseLong(raw.getString(0)), - Long.parseLong(raw.getString(1)) - }); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #touch(String[], Options, ResponseListener)} - */ - public MemoryStorage touch(String[] keys) { - return touch(keys, null, null); - } - - /** - * {@link #touch(String[], Options, ResponseListener)} - */ - public MemoryStorage touch(String[] keys, Options options) { - return touch(keys, options, null); - } - - /** - * {@link #touch(String[], Options, ResponseListener)} - */ - public MemoryStorage touch(String[] keys, final ResponseListener listener) { - return touch(keys, null, listener); - } - - /** - * Alters the last access time of one or multiple keys. - * A key is ignored if it does not exist. - * @param keys Array of key IDs to alter - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage touch(String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("body", new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys)))); - - send("touch", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #ttl(String, Options, ResponseListener)} - */ - public void ttl(String key, final ResponseListener listener) { - ttl(key, null, listener); - } - - /** - * Returns the remaining time to live of a key, in seconds, or a negative value - * if the key does not exist or if it is persistent. - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - */ - public void ttl(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("ttl", query, options, getCallbackLong(listener)); - } - - /** - * {@link #type(String, Options, ResponseListener)} - */ - public void type(String key, final ResponseListener listener) { - type(key, null, listener); - } - - /** - * Returns the type of the value held by a key. - * @param key Key ID - * @param options Request options - * @param listener Response callback listener - */ - public void type(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("type", query, options, getCallbackString(listener)); - } - - /** - * {@link #zadd(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage zadd(String key, JSONObject[] elements) { - return zadd(key, elements, null, null); - } - - /** - * {@link #zadd(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage zadd(String key, JSONObject[] elements, final ResponseListener listener) { - return zadd(key, elements, null, listener); - } - - /** - * {@link #zadd(String, JSONObject[], Options, ResponseListener)} - */ - public MemoryStorage zadd(String key, JSONObject[] elements, Options options) { - return zadd(key, elements, options, null); - } - - /** - * Adds the specified elements to the sorted set stored at key. - * If the key does not exist, it is created, holding an empty sorted set. - * If it already exists and does not hold a sorted set, an error is returned. - * @param key Sorted set ID - * @param elements Elements to add - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage zadd(String key, JSONObject[] elements, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - KuzzleJSONObject body = new KuzzleJSONObject().put("elements", new JSONArray(Arrays.asList(elements))); - - if (options != null) { - body.put("nx", options.getNx()); - body.put("xx", options.getXx()); - body.put("ch", options.getCh()); - body.put("incr", options.getIncr()); - } - - query.put("body", body); - - send("zadd", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #zcard(String, Options, ResponseListener)} - */ - public void zcard(String key, final ResponseListener listener) { - zcard(key, null, listener); - } - - /** - * Returns the number of elements held by a sorted set. - * @param key Sorted set ID - * @param options Request options - * @param listener Response callback listener - */ - public void zcard(String key, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key); - - send("zcard", query, options, getCallbackLong(listener)); - } - - /** - * {@link #zcount(String, long, long, Options, ResponseListener)} - */ - public void zcount(String key, long min, long max, final ResponseListener listener) { - zcount(key, min, max, null, listener); - } - - /** - * Returns the number of elements held by a sorted set - * with a score between the provided min and max values. - * @param key Sorted set ID - * @param min Minimum score - * @param max Maximum score - * @param options Request options - * @param listener Response callback listener - */ - public void zcount(String key, long min, long max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("min", min) - .put("max", max); - - send("zcount", query, options, getCallbackLong(listener)); - } - - /** - * {@link #zincrby(String, String, double, Options, ResponseListener)} - */ - public MemoryStorage zincrby(String key, String member, double value) { - return zincrby(key, member, value, null, null); - } - - /** - * {@link #zincrby(String, String, double, Options, ResponseListener)} - */ - public MemoryStorage zincrby(String key, String member, double value, final ResponseListener listener) { - return zincrby(key, member, value, null, listener); - } - - /** - * {@link #zincrby(String, String, double, Options, ResponseListener)} - */ - public MemoryStorage zincrby(String key, String member, double value, Options options) { - return zincrby(key, member, value, options, null); - } - - /** - * Increments the score of a member in a sorted set by the provided value. - * @param key Sorted set ID - * @param member Member to increment - * @param value Increment value - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage zincrby(String key, String member, double value, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("member", member) - .put("value", value) - ); - - - send("zincrby", query, options, listener != null ? getCallbackDouble(listener) : null); - - return this; - } - - /** - * {@link #zinterstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zinterstore(String destination, String[] keys) { - return zinterstore(destination, keys, null, null); - } - - /** - * {@link #zinterstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zinterstore(String destination, String[] keys, final ResponseListener listener) { - return zinterstore(destination, keys, null, listener); - } - - /** - * {@link #zinterstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zinterstore(String destination, String[] keys, Options options) { - return zinterstore(destination, keys, options, null); - } - - /** - * Computes the intersection of the provided sorted sets and - * stores the result in the destination key. - * @param destination Destination ID - * @param keys Array of sorted set IDs - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage zinterstore(String destination, String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", destination); - KuzzleJSONObject body = new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys))); - - if (options != null) { - if (options.getAggregate() != null) { - body.put("aggregate", options.getAggregate()); - } - - if (options.getWeights() != null) { - body.put("weights", new JSONArray(Arrays.asList(options.getWeights()))); - } - } - - query.put("body", body); - - send("zinterstore", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #zlexcount(String, String, String, Options, ResponseListener)} - */ - public void zlexcount(String key, String min, String max, final ResponseListener listener) { - zlexcount(key, min, max, null, listener); - } - - /** - * Counts elements in a sorted set where all members have equal - * score, using lexicographical ordering. - * @param key Sorted set ID - * @param min Minimum value - * @param max Maximum value - * @param options Request options - * @param listener Response callback listener - */ - public void zlexcount(String key, String min, String max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("min", min) - .put("max", max); - - send("zlexcount", query, options, getCallbackLong(listener)); - } - - /** - * {@link #zrange(String, long, long, Options, ResponseListener)} - */ - public void zrange(String key, long start, long stop, final ResponseListener listener) { - zrange(key, start, stop, null, listener); - } - - /** - * Returns elements from a sorted set depending on their position in the set, - * from a start position index to a stop position index (inclusives). - * @param key Sorted set ID - * @param start Start position - * @param stop End position - * @param options Request options - * @param listener Response callback listener - */ - public void zrange(String key, long start, long stop, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("start", start) - .put("stop", stop) - .put("options", new JSONArray().put("withscores")); - - send( - "zrange", - query, - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(mapZrangeResults(response.getJSONArray("result"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #zrangebylex(String, String, String, Options, ResponseListener)} - */ - public void zrangebylex(String key, String min, String max, final ResponseListener listener) { - zrangebylex(key, min, max, null, listener); - } - - /** - * Returns elements in a sorted set where all members have equal - * score, using lexicographical ordering. - * @param key Sorted set ID - * @param min Minimum value - * @param max Maximum value - * @param options Request options - * @param listener Response callback listener - */ - public void zrangebylex(String key, String min, String max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("min", min) - .put("max", max); - - if (options != null) { - if (options.getLimit() != null) { - query.put("limit", new JSONArray(Arrays.asList(options.getLimit()))); - } - } - - send("zrangebylex", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #zrangebyscore(String, double, double, Options, ResponseListener)} - */ - public void zrangebyscore(String key, double min, double max, final ResponseListener listener) { - zrangebyscore(key, min, max, null, listener); - } - - /** - * Returns all the elements in the sorted set at key with a - * score between min and max (inclusive). T - * @param key Sorted set ID - * @param min Minimum score - * @param max Maximum score - * @param options Request options - * @param listener Response callback listener - */ - public void zrangebyscore(String key, double min, double max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("min", min) - .put("max", max) - .put("options", new JSONArray().put("withscores")); - - if (options != null) { - if (options.getLimit() != null) { - query.put("limit", new JSONArray(Arrays.asList(options.getLimit()))); - } - } - - send( - "zrangebyscore", - query, - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(mapZrangeResults(response.getJSONArray("result"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #zrank(String, String, Options, ResponseListener)} - */ - public void zrank(String key, String member, final ResponseListener listener) { - zrank(key, member, null, listener); - } - - /** - * Returns the position of an element in a sorted set, with scores in ascending order. - * @param key Sorted set ID - * @param member Member value - * @param options Request options - * @param listener Response callback listener - */ - public void zrank(String key, String member, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("member", member); - - send("zrank", query, options, getCallbackLong(listener)); - } - - /** - * {@link #zrem(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zrem(String key, String[] members) { - return zrem(key, members, null, null); - } - - /** - * {@link #zrem(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zrem(String key, String[] members, final ResponseListener listener) { - return zrem(key, members, null, listener); - } - - /** - * {@link #zrem(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zrem(String key, String[] members, Options options) { - return zrem(key, members, options, null); - } - - /** - * Removes members from a sorted set. - * @param key Sorted set ID - * @param members Members to remove - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage zrem(String key, String[] members, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("members", new JSONArray(Arrays.asList(members))) - ); - - send("zrem", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #zremrangebylex(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage zremrangebylex(String key, String min, String max) { - return zremrangebylex(key, min, max, null, null); - } - - /** - * {@link #zremrangebylex(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage zremrangebylex(String key, String min, String max, final ResponseListener listener) { - return zremrangebylex(key, min, max, null, listener); - } - - /** - * {@link #zremrangebylex(String, String, String, Options, ResponseListener)} - */ - public MemoryStorage zremrangebylex(String key, String min, String max, Options options) { - return zremrangebylex(key, min, max, options, null); - } - - /** - * Removes members from a sorted set where all elements have - * the same score, using lexicographical ordering. - * @param key Sorted set ID - * @param min Minimum value - * @param max Maximum value - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage zremrangebylex(String key, String min, String max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("min", min) - .put("max", max) - ); - - send("zremrangebylex", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #zremrangebyrank(String, long, long, Options, ResponseListener)} - */ - public MemoryStorage zremrangebyrank(String key, long min, long max) { - return zremrangebyrank(key, min, max, null, null); - } - - /** - * {@link #zremrangebyrank(String, long, long, Options, ResponseListener)} - */ - public MemoryStorage zremrangebyrank(String key, long min, long max, final ResponseListener listener) { - return zremrangebyrank(key, min, max, null, listener); - } - - /** - * {@link #zremrangebyrank(String, long, long, Options, ResponseListener)} - */ - public MemoryStorage zremrangebyrank(String key, long min, long max, Options options) { - return zremrangebyrank(key, min, max, options, null); - } - - /** - * Removes members from a sorted set with their position - * in the set - * @param key Sorted set ID - * @param min Start position - * @param max End position - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage zremrangebyrank(String key, long min, long max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("start", min) - .put("stop", max) - ); - - send("zremrangebyrank", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #zremrangebyscore(String, double, double, Options, ResponseListener)} - */ - public MemoryStorage zremrangebyscore(String key, double min, double max) { - return zremrangebyscore(key, min, max, null, null); - } - - /** - * {@link #zremrangebyscore(String, double, double, Options, ResponseListener)} - */ - public MemoryStorage zremrangebyscore(String key, double min, double max, final ResponseListener listener) { - return zremrangebyscore(key, min, max, null, listener); - } - - /** - * {@link #zremrangebyscore(String, double, double, Options, ResponseListener)} - */ - public MemoryStorage zremrangebyscore(String key, double min, double max, Options options) { - return zremrangebyscore(key, min, max, options, null); - } - - /** - * Removes members from a sorted set with a score - * @param key Sorted set ID - * @param min Minimum score - * @param max Maximum score - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage zremrangebyscore(String key, double min, double max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("body", new KuzzleJSONObject() - .put("min", min) - .put("max", max) - ); - - send("zremrangebyscore", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } - - /** - * {@link #zrevrange(String, long, long, Options, ResponseListener)} - */ - public void zrevrange(String key, long start, long stop, final ResponseListener listener) { - zrevrange(key, start, stop, null, listener); - } - - /** - * Identical to zrange, except that the sorted set is traversed in descending order. - * @param key Sorted set ID - * @param start Start position - * @param stop End position - * @param options Request options - * @param listener Response callback listener - */ - public void zrevrange(String key, long start, long stop, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("start", start) - .put("stop", stop) - .put("options", new JSONArray().put("withscores")); - - send( - "zrevrange", - query, - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(mapZrangeResults(response.getJSONArray("result"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #zrevrangebylex(String, String, String, Options, ResponseListener)} - */ - public void zrevrangebylex(String key, String min, String max, final ResponseListener listener) { - zrevrangebylex(key, min, max, null, listener); - } - - /** - * Identical to zrangebylex except that the sorted set is traversed in descending order. - * @param key Sorted set ID - * @param min Minimum value - * @param max Maximum value - * @param options Request options - * @param listener Response callback listener - */ - public void zrevrangebylex(String key, String min, String max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("min", min) - .put("max", max); - - if (options != null) { - if (options.getLimit() != null) { - query.put("limit", new JSONArray(Arrays.asList(options.getLimit()))); - } - } - - send("zrevrangebylex", query, options, getCallbackStringArray(listener)); - } - - /** - * {@link #zrevrangebyscore(String, double, double, Options, ResponseListener)} - */ - public void zrevrangebyscore(String key, double min, double max, final ResponseListener listener) { - zrevrangebyscore(key, min, max, null, listener); - } - - /** - * Identical to zrangebyscore except that the sorted set is traversed in descending order. - * @param key Sorted set ID - * @param min Minimum score - * @param max Maximum score - * @param options Request options - * @param listener Response callback listener - */ - public void zrevrangebyscore(String key, double min, double max, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("min", min) - .put("max", max) - .put("options", new JSONArray().put("withscores")); - - if (options != null) { - if (options.getLimit() != null) { - query.put("limit", new JSONArray(Arrays.asList(options.getLimit()))); - } - } - - send( - "zrevrangebyscore", - query, - options, - new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(mapZrangeResults(response.getJSONArray("result"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - } - ); - } - - /** - * {@link #zrevrank(String, String, Options, ResponseListener)} - */ - public void zrevrank(String key, String member, final ResponseListener listener) { - zrevrank(key, member, null, listener); - } - - /** - * Returns the position of an element in a sorted set, with scores in descending order. - * @param key Sorted set ID - * @param member Member value - * @param options Request options - * @param listener Response callback listener - */ - public void zrevrank(String key, String member, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("member", member); - - send("zrevrank", query, options, getCallbackLong(listener)); - } - - /** - * {@link #zscan(String, long, Options, ResponseListener)} - */ - public void zscan(String key, long cursor, final ResponseListener listener) { - zscan(key, cursor, null, listener); - } - - /** - * Identical to scan, except that zscan iterates the members held by a sorted set. - * @param key Sorted set ID - * @param cursor Cursor position (0 to start an iteration) - * @param options Request options - * @param listener Response callback listener - */ - public void zscan(String key, long cursor, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject() - .put("_id", key) - .put("cursor", cursor); - - if (options != null) { - if (options.getCount() != null) { - query.put("count", options.getCount()); - } - - if (options.getMatch() != null) { - query.put("match", options.getMatch()); - } - } - - send("zscan", query, options, getCallbackScanResult(listener)); - } - - /** - * {@link #zscore(String, String, Options, ResponseListener)} - */ - public void zscore(String key, String member, final ResponseListener listener) { - zscore(key, member, null, listener); - } - - /** - * Returns the score of a member in a sorted set. - * @param key Sorted set ID - * @param member Member value - * @param options Request options - * @param listener Response callback listener - */ - public void zscore(String key, String member, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", key).put("member", member); - - send("zscore", query, options, getCallbackDouble(listener)); - } - - /** - * {@link #zunionstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zunionstore(String destination, String[] keys) { - return zunionstore(destination, keys, null, null); - } - - /** - * {@link #zunionstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zunionstore(String destination, String[] keys, final ResponseListener listener) { - return zunionstore(destination, keys, null, listener); - } - - /** - * {@link #zunionstore(String, String[], Options, ResponseListener)} - */ - public MemoryStorage zunionstore(String destination, String[] keys, Options options) { - return zunionstore(destination, keys, options, null); - } - - /** - * Computes the union of the provided sorted sets and stores the result in the destination key. - * @param destination Destination key ID - * @param keys Array of sorted set IDs - * @param options [description] - * @param listener [description] - * @return this - */ - public MemoryStorage zunionstore(String destination, String[] keys, Options options, final ResponseListener listener) { - KuzzleJSONObject query = new KuzzleJSONObject().put("_id", destination); - KuzzleJSONObject body = new KuzzleJSONObject().put("keys", new JSONArray(Arrays.asList(keys))); - - if (options != null) { - if (options.getAggregate() != null) { - body.put("aggregate", options.getAggregate()); - } - - if (options.getWeights() != null) { - body.put("weights", new JSONArray(Arrays.asList(options.getWeights()))); - } - } - - query.put("body", body); - - send("zunionstore", query, options, listener != null ? getCallbackLong(listener) : null); - - return this; - } -} diff --git a/src/main/java/io/kuzzle/sdk/core/Options.java b/src/main/java/io/kuzzle/sdk/core/Options.java deleted file mode 100644 index 45230045..00000000 --- a/src/main/java/io/kuzzle/sdk/core/Options.java +++ /dev/null @@ -1,982 +0,0 @@ -package io.kuzzle.sdk.core; - - - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import io.kuzzle.sdk.enums.CollectionType; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.responses.SearchResult; - -public class Options { - // Default values - private boolean autoQueue = false; - private boolean autoReconnect = true; - private boolean autoReplay = false; - private boolean autoResubscribe = true; - private JSONObject headers = new JSONObject(); - private JSONObject _volatile = new JSONObject(); - private int queueMaxSize = 500; - private int queueTTL = 120000; - private long reconnectionDelay = 1000; - private String ifExist = "error"; - private Mode connect = Mode.AUTO; - private Mode offlineMode = Mode.MANUAL; - private int replayInterval = 10; - private boolean queuable = true; - private String defaultIndex = null; - private boolean replaceIfExist = false; - private String refresh = null; - private Long from = null; - private Long size = null; - private Integer port = 7512; - private String scroll = null; - - private boolean ssl = false; - private SearchResult previous = null; - private String scrollId = null; - private int retryOnConflict = 0; - - // MemoryStorage specific options - private Long start = null; - private Long end = null; - private String unit = null; - private boolean withcoord = false; - private boolean withdist = false; - private Long count = null; - private String sort = null; - private String match = null; - private Long ex = null; - private boolean nx = false; - private Long px = null; - private boolean xx = false; - private boolean alpha = false; - private String by = null; - private String direction = null; - private String[] get = null; - private Integer[] limit = null; - private boolean ch = false; - private boolean incr = false; - private String aggregate = null; - private Integer[] weights = null; - - // Used for getting collections - private CollectionType collectionType = CollectionType.ALL; - - public Options() { - // Default constructor - } - - public Options(Options originalOptions) throws JSONException { - this.autoQueue = originalOptions.autoQueue; - this.autoReconnect = originalOptions.autoReconnect; - this.autoResubscribe = originalOptions.autoResubscribe; - this.headers = new JSONObject(originalOptions.headers.toString()); - this._volatile = new JSONObject(originalOptions._volatile.toString()); - this.queueMaxSize = originalOptions.queueMaxSize; - this.queueTTL = originalOptions.queueTTL; - this.reconnectionDelay = originalOptions.reconnectionDelay; - this.ifExist = originalOptions.ifExist; - this.connect = originalOptions.connect; - this.offlineMode = originalOptions.offlineMode; - this.replayInterval = originalOptions.replayInterval; - this.queuable = originalOptions.queuable; - this.defaultIndex = originalOptions.defaultIndex; - this.replaceIfExist = originalOptions.replaceIfExist; - this.refresh = originalOptions.refresh; - this.from = originalOptions.from; - this.size = originalOptions.size; - this.port = originalOptions.port; - this.scroll = originalOptions.scroll; - this.previous = originalOptions.previous; - this.scrollId = originalOptions.scrollId; - } - - /** - * autoReconnect option getter - * - * @return isAutoReconnection option value - */ - public boolean isAutoReconnect() { - return autoReconnect; - } - - /** - * autoReconnect option setter - * - * @param autoReconnect New autoReconnect option value - * @return this - */ - public Options setAutoReconnect(boolean autoReconnect) { - this.autoReconnect = autoReconnect; - return this; - } - - /** - * headers getter - * - * @return headers option value - */ - public JSONObject getHeaders() { - return headers; - } - - /** - * headers setter - * - * @param headers New headers value - * @return this - */ - public Options setHeaders(JSONObject headers) { - this.headers = headers; - return this; - } - - /** - * exists option getter - * - * @return exists option value - */ - public String getIfExist() { - return ifExist; - } - - /** - * exists option setter - * - * @param value new exists option value - * @return this - */ - public Options setIfExist(String value) { - if (value != "error" && value != "replace") { - throw new IllegalArgumentException("Invalid value for option 'ifExists': " + value); - } - - this.ifExist = value; - return this; - } - - /** - * Gets volatile data. - * - * @return the volatile property - */ - public JSONObject getVolatile() { - return _volatile; - } - - /** - * Sets volatile data. - * - * @param _volatile new volatile data value - * @return this - */ - public Options setVolatile(JSONObject _volatile) { - this._volatile = _volatile; - return this; - } - - /** - * Gets connect property value - * - * @return the connect property value - */ - public Mode getConnect() { - return connect; - } - - /** - * Sets connect property value - * - * @param connect New connect property value - * @return this - */ - public Options setConnect(Mode connect) { - this.connect = connect; - return this; - } - - /** - * reconnectionDelay property getter - * - * @return the reconnectionDelay property value - */ - public long getReconnectionDelay() { - return reconnectionDelay; - } - - /** - * reconnectionDelay property setter - * - * @param reconnectionDelay New reconnectionDelay property value - * @return this - */ - public Options setReconnectionDelay(long reconnectionDelay) { - this.reconnectionDelay = reconnectionDelay; - return this; - } - - /** - * offlineMode property getter - * - * @return the offlineMode option value - */ - public Mode getOfflineMode() { - return offlineMode; - } - - /** - * offlineMode property setter - * - * @param offlineMode New offlineMode value - * @return this - */ - public Options setOfflineMode(Mode offlineMode) { - this.offlineMode = offlineMode; - return this; - } - - /** - * queueTTL property getter - * - * @return queueTTL property value - */ - public int getQueueTTL() { - return queueTTL; - } - - /** - * queueTTL property setter - * - * @param queueTTL New queueTTL value - * @return this - */ - public Options setQueueTTL(int queueTTL) { - this.queueTTL = queueTTL; - return this; - } - - /** - * autoReplay property getter - * - * @return autoReplay property value - */ - public boolean isAutoReplay() { - return autoReplay; - } - - /** - * autoReplay property setter - * - * @param autoReplay New autoReplay value - * @return this - */ - public Options setAutoReplay(boolean autoReplay) { - this.autoReplay = autoReplay; - return this; - } - - /** - * queuable property getter - * - * @return queuable property value - */ - public boolean isQueuable() { - return queuable; - } - - /** - * queuable property setter - * - * @param queuable New queuable value - * @return this - */ - public Options setQueuable(boolean queuable) { - this.queuable = queuable; - return this; - } - - /** - * queueMaxSize property getter - * - * @return queueMaxSize value - */ - public int getQueueMaxSize() { - return queueMaxSize; - } - - /** - * queueMaxSize property setter - * - * @param queueMaxSize New queueMaxSize value - * @return this - */ - public Options setQueueMaxSize(int queueMaxSize) { - this.queueMaxSize = queueMaxSize; - return this; - } - - /** - * replayInterval property getter - * - * @return replayInterval property value - */ - public int getReplayInterval() { - return replayInterval; - } - - /** - * replayInterval property setter - * - * @param replayInterval New replayInterval value - * @return this - */ - public Options setReplayInterval(int replayInterval) { - this.replayInterval = replayInterval; - return this; - } - - /** - * autoResubscribe property getter - * - * @return autoResubscribe property value - */ - public boolean isAutoResubscribe() { - return autoResubscribe; - } - - /** - * autoResubscribe property setter - * - * @param autoResubscribe New autoResubscribe value - * @return this - */ - public Options setAutoResubscribe(boolean autoResubscribe) { - this.autoResubscribe = autoResubscribe; - return this; - } - - /** - * collectionType property getter - * - * @return collectionType property value - */ - public CollectionType getCollectionType() { - return collectionType; - } - - /** - * collectionType property setter - * - * @param type New collectionType value - * @return this - */ - public Options setCollectionType(CollectionType type) { - this.collectionType = type; - return this; - } - - /** - * defaultIndex property setter - * - * @param index New defaultIndex value - * @return this - */ - public Options setDefaultIndex(final String index) { - this.defaultIndex = index; - return this; - } - - /** - * defaultIndex property getter - * - * @return defaultIndex property value - */ - public String getDefaultIndex() { - return this.defaultIndex; - } - - /** - * autoQueue property setter - * - * @param autoQueue New autoQueue value - * @return this - */ - public Options setAutoQueue(boolean autoQueue) { - this.autoQueue = autoQueue; - return this; - } - - /** - * autoQueue property getter - * - * @return autoQueue property value - */ - public boolean isAutoQueue() { - return this.autoQueue; - } - - /** - * replaceIfExist property setter - * - * @param replace New replaceIfExist value - * @return this - */ - public Options setReplaceIfExist(boolean replace) { - this.replaceIfExist = replace; - return this; - } - - /** - * replaceIfExist property getter - * - * @return replaceIfExist property value - */ - public boolean isReplaceIfExist() { - return this.replaceIfExist; - } - - /** - * from property getter - * @return from property value - */ - public Long getFrom() { - return from; - } - - /** - * from property setter - * @param from New from value - * @return this - */ - public Options setFrom(Long from) { - this.from = from; - return this; - } - - /** - * size property getter - * @return size property value - */ - public Long getSize() { - return size; - } - - /** - * size property setter - * @param size New size value - * @return this - */ - public Options setSize(Long size) { - this.size = size; - return this; - } - - /** - * port property setter - * @param port New port value - * @return this - */ - public Options setPort(Integer port) { - this.port = port; - return this; - } - - /** - * port property getter - * @return port property value - */ - public Integer getPort() { - return this.port; - } - - /** - * ssl property getter - * @return ssl property value - */ - public boolean isSsl() { - return ssl; - } - - /** - * ssl property setter - * @param ssl New port value - */ - public void setSsl(boolean ssl) { - this.ssl = ssl; - } - - /** - * refresh property getter - * @return refresh property value - */ - public String getRefresh() { - return refresh; - } - - /** - * refresh property setter - * @param refresh New refresh property value - * @return [description] - */ - public Options setRefresh(String refresh) { - this.refresh = refresh; - return this; - } - - /** - * scroll property getter - * @return scroll property value - */ - public String getScroll() { - return scroll; - } - - /** - * scroll property setter - * @param scroll New scroll value - * @return this - */ - public Options setScroll(String scroll) { - this.scroll = scroll; - return this; - } - - /** - * previous property getter - * @return previous property value - */ - public SearchResult getPrevious() { - return previous; - } - - /** - * previous property setter - * @param previous New previous value - * @return this - */ - public Options setPrevious(SearchResult previous) { - this.previous = previous; - return this; - } - - /** - * scrollId property getter - * @return scrollId property value - */ - public String getScrollId() { - return scrollId; - } - - /** - * scrollId property setter - * @param scrollId New scrollId value - * @return this - */ - public Options setScrollId(String scrollId) { - this.scrollId = scrollId; - return this; - } - - /** - * retryOnConflict property getter - * @return retryOnConflict property value - */ - public int getRetryOnConflict() { - return retryOnConflict; - } - - /** - * retryOnConflict property setter - * @param retryOnConflict New retryOnConflict value - * @return this - */ - public Options setRetryOnConflict(int retryOnConflict) { - if (retryOnConflict < 0) { - throw new IllegalArgumentException("Invalid value for the retryOnConflict option (positive or null integer allowed)"); - } - - this.retryOnConflict = retryOnConflict; - return this; - } - - /** - * start property getter - * @return start property value - */ - public Long getStart() { - return start; - } - - /** - * start property setter - * @param start New start value - * @return this - */ - public Options setStart(Long start) { - this.start = start; - return this; - } - - /** - * end property getter - * @return end property value - */ - public Long getEnd() { - return end; - } - - /** - * end property setter - * @param end New end value - * @return this - */ - public Options setEnd(Long end) { - this.end = end; - return this; - } - - /** - * unit property getter - * @return unit property value - */ - public String getUnit() { - return unit; - } - - /** - * unit property setter - * @param unit New unit value - * @return this - */ - public Options setUnit(String unit) { - this.unit = unit; - return this; - } - - /** - * withcoord property getter - * @return withcoord property value - */ - public boolean getWithcoord() { - return withcoord; - } - - /** - * withcoord property setter - * @param withcoord New withcoord value - * @return this - */ - public Options setWithcoord(boolean withcoord) { - this.withcoord = withcoord; - return this; - } - - /** - * withdist property getter - * @return withdist property value - */ - public boolean getWithdist() { - return withdist; - } - - /** - * withdist property setter - * @param withdist New withdist value - * @return this - */ - public Options setWithdist(boolean withdist) { - this.withdist = withdist; - return this; - } - - /** - * count property getter - * @return count property value - */ - public Long getCount() { - return count; - } - - /** - * count property setter - * @param count New count value - * @return this - */ - public Options setCount(Long count) { - this.count = count; - return this; - } - - /** - * sort property getter - * @return sort property value - */ - public String getSort() { - return sort; - } - - /** - * sort property setter - * @param sort New sort value - * @return this - */ - public Options setSort(String sort) { - this.sort = sort; - return this; - } - - /** - * match property getter - * @return match property value - */ - public String getMatch() { - return match; - } - - /** - * match property setter - * @param match New match value - * @return this - */ - public Options setMatch(String match) { - this.match = match; - return this; - } - - /** - * ex property getter - * @return ex property value - */ - public Long getEx() { - return ex; - } - - /** - * ex property setter - * @param ex New ex value - * @return this - */ - public Options setEx(Long ex) { - this.ex = ex; - return this; - } - - /** - * nx property getter - * @return nx property value - */ - public boolean getNx() { - return nx; - } - - /** - * nx property setter - * @param nx New nx value - * @return this - */ - public Options setNx(boolean nx) { - this.nx = nx; - return this; - } - - /** - * px property getter - * @return px property value - */ - public Long getPx() { - return px; - } - - /** - * px property setter - * @param px New px value - * @return this - */ - public Options setPx(Long px) { - this.px = px; - return this; - } - - /** - * xx property getter - * @return xx property value - */ - public boolean getXx() { - return xx; - } - - /** - * xx property setter - * @param xx New xx value - * @return this - */ - public Options setXx(boolean xx) { - this.xx = xx; - return this; - } - - /** - * alpha property getter - * @return alpha property value - */ - public boolean getAlpha() { - return alpha; - } - - /** - * alpha property setter - * @param alpha New alpha value - * @return this - */ - public Options setAlpha(boolean alpha) { - this.alpha = alpha; - return this; - } - - /** - * by property getter - * @return by property value - */ - public String getBy() { - return by; - } - - /** - * by property setter - * @param by New by value - * @return this - */ - public Options setBy(String by) { - this.by = by; - return this; - } - - /** - * direction property getter - * @return direction property value - */ - public String getDirection() { - return direction; - } - - /** - * direction property setter - * @param direction New direction value - * @return this - */ - public Options setDirection(String direction) { - this.direction = direction; - return this; - } - - /** - * get property getter - * @return get property value - */ - public String[] getGet() { - return get; - } - - /** - * get property setter - * @param get New get value - * @return this - */ - public Options setGet(String[] get) { - this.get = get; - return this; - } - - /** - * limit property getter - * @return limit property value - */ - public Integer[] getLimit() { - return limit; - } - - /** - * limit property setter - * @param limit New limit value - * @return this - */ - public Options setLimit(Integer[] limit) { - this.limit = limit; - return this; - } - - /** - * ch property getter - * @return ch property value - */ - public boolean getCh() { - return ch; - } - - /** - * ch property setter - * @param ch New ch value - * @return this - */ - public Options setCh(boolean ch) { - this.ch = ch; - return this; - } - - /** - * incr property getter - * @return incr property value - */ - public boolean getIncr() { - return incr; - } - - /** - * incr property setter - * @param incr New incr value - * @return this - */ - public Options setIncr(boolean incr) { - this.incr = incr; - return this; - } - - /** - * aggregate property getter - * @return aggregate property value - */ - public String getAggregate() { - return aggregate; - } - - /** - * aggregate property setter - * @param aggregate New aggregate value - * @return this - */ - public Options setAggregate(String aggregate) { - this.aggregate = aggregate; - return this; - } - - /** - * weights property getter - * @return weights property value - */ - public Integer[] getWeights() { - return weights; - } - - /** - * weights property setter - * @param weights New weights value - * @return this - */ - public Options setWeights(Integer[] weights) { - this.weights = weights; - return this; - } -} diff --git a/src/main/java/io/kuzzle/sdk/core/Room.java b/src/main/java/io/kuzzle/sdk/core/Room.java deleted file mode 100644 index e81b55f7..00000000 --- a/src/main/java/io/kuzzle/sdk/core/Room.java +++ /dev/null @@ -1,560 +0,0 @@ -package io.kuzzle.sdk.core; - - - -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Scope; -import io.kuzzle.sdk.enums.State; -import io.kuzzle.sdk.enums.Users; -import io.kuzzle.sdk.listeners.EventListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.SubscribeListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.NotificationResponse; -import io.kuzzle.sdk.state.States; - -public class Room { - - private String id = UUID.randomUUID().toString(); - protected String collection; - protected Collection dataCollection; - protected JSONObject filters = new JSONObject(); - protected JSONObject headers; - protected JSONObject _volatile; - protected boolean subscribeToSelf; - protected String roomId; - protected Kuzzle kuzzle; - protected String channel; - protected Scope scope; - protected State state; - protected Users users; - protected ResponseListener listener; - - // Used to avoid subscription renewals to trigger multiple times because of - // multiple but similar events - private long lastRenewal = 0; - private long renewalDelay = 500; - - // Used to delay method calls when subscription is in progress - protected boolean subscribing = false; - private ArrayList queue = new ArrayList<>(); - private SubscribeListener doneListener; - - /** - * Constructor - * - * @param kuzzleDataCollection Data collection to link - */ - public Room(final Collection kuzzleDataCollection) { - this(kuzzleDataCollection, null); - } - - /** - * This object is the result of a subscription request, allowing to manipulate the subscription itself. - * In Kuzzle, you don't exactly subscribe to a room or a topic but, instead, you subscribe to documents. - * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters. - * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored - * document change (because it is created, updated or deleted), then you'll receive a notification about it. - * - * @param kuzzleDataCollection Data collection to link - * @param options Subscription options - */ - public Room(final Collection kuzzleDataCollection, final RoomOptions options) { - RoomOptions opts = options != null ? options : new RoomOptions(); - - if (kuzzleDataCollection == null) { - throw new IllegalArgumentException("Room: missing dataCollection"); - } - kuzzleDataCollection.getKuzzle().isValid(); - - this.dataCollection = kuzzleDataCollection; - this.kuzzle = kuzzleDataCollection.getKuzzle(); - this.collection = kuzzleDataCollection.getCollection(); - - try { - this.headers = new JSONObject(kuzzleDataCollection.getHeaders().toString()); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - - this.subscribeToSelf = opts.isSubscribeToSelf(); - this._volatile = opts.getVolatile(); - this.scope = opts.getScope(); - this.state = opts.getState(); - this.users = opts.getUsers(); - } - - /** - * Returns the number of other subscriptions on that room. - * - * @param listener Response callback listener - */ - public void count(final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Room.count: a callback listener is required"); - } - - // Delays this call until after the subscription is finished - if (!this.isReady()) { - this.queue.add(new Runnable() { - @Override - public void run() { - Room.this.count(listener); - } - }); - return; - } - - if (this.roomId == null) { - throw new IllegalStateException("Room.count: cannot count subscriptions on an inactive room"); - } - - try { - JSONObject data = new JSONObject().put("body", new JSONObject().put("roomId", this.roomId)); - this.kuzzle.addHeaders(data, this.headers); - - this.kuzzle.query(this.dataCollection.makeQueryArgs("realtime", "count"), data, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result").getInt("count")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * Call after renew. - * - * @param args the args - */ - protected void callAfterRenew(final Object args) { - if (args == null) { - throw new IllegalArgumentException("Room.renew: response required"); - } - - try { - String requestId = ((JSONObject) args).has("requestId") ? ((JSONObject) args).getString("requestId") : null; - - if (((JSONObject) args).getString("type").equals("TokenExpired")) { - Room.this.kuzzle.jwtToken = null; - Room.this.kuzzle.emitEvent(Event.tokenExpired); - } - - if (requestId != null && Room.this.kuzzle.getRequestHistory().containsKey(requestId)) { - if (Room.this.subscribeToSelf) { - listener.onSuccess(new NotificationResponse(kuzzle, (JSONObject) args)); - } - Room.this.kuzzle.getRequestHistory().remove(requestId); - } else { - listener.onSuccess(new NotificationResponse(kuzzle, (JSONObject) args)); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #renew(JSONObject, ResponseListener, SubscribeListener)} - */ - public Room renew(final ResponseListener listener) { - return this.renew(null, listener, null); - } - - /** - * {@link #renew(JSONObject, ResponseListener, SubscribeListener)} - */ - public Room renew(final ResponseListener listener, final SubscribeListener subscribeResponseListener) { - return this.renew(null, listener, subscribeResponseListener); - } - - /** - * Renew the subscription. Force a resubscription using the same filters - * if no new ones are provided. - * Unsubscribes first if this Room was already listening to events. - * - * @param filters Subscription filters, using Kuzzle DSL - * @param listener Response callback listener - * @return this - */ - public Room renew(final JSONObject filters, final ResponseListener listener, final SubscribeListener subscribeResponseListener) { - long now = System.currentTimeMillis(); - - if (listener == null) { - throw new IllegalArgumentException("Room.renew: a callback listener is required"); - } - - // Skip subscription renewal if another one was performed just a moment before - if (this.lastRenewal > 0 && (now - this.lastRenewal) <= this.renewalDelay) { - return this; - } - - if (filters != null) { - this.filters = filters; - } - - /* - If not yet connected, registers itself into the subscriptions list and wait for the - main Kuzzle object to renew subscriptions once online - */ - if (this.kuzzle.state != States.CONNECTED) { - this.listener = listener; - this.doneListener = subscribeResponseListener; - this.kuzzle.addPendingSubscription(this.id, this); - return this; - } - - if (this.subscribing) { - this.queue.add(new Runnable() { - @Override - public void run() { - Room.this.renew(filters, listener, subscribeResponseListener); - } - }); - - return this; - } - - this.unsubscribe(); - this.roomId = null; - this.subscribing = true; - this.listener = listener; - this.doneListener = subscribeResponseListener; - this.kuzzle.addPendingSubscription(this.id, this); - - try { - final Options options = new Options(); - final JSONObject - subscribeQuery = new JSONObject() - .put("body", this.filters) - .put("scope", this.scope.toString().toLowerCase()) - .put("state", this.state.toString().toLowerCase()) - .put("users", this.users.toString().toLowerCase()); - - options.setVolatile(this._volatile); - this.kuzzle.addHeaders(subscribeQuery, this.headers); - - new Thread(new Runnable() { - @Override - public void run() { - try { - Room.this.kuzzle.query(Room.this.dataCollection.makeQueryArgs("realtime", "subscribe"), subscribeQuery, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject args) { - try { - Room.this.kuzzle.deletePendingSubscription(Room.this.id); - Room.this.subscribing = false; - Room.this.lastRenewal = System.currentTimeMillis(); - - JSONObject result = args.getJSONObject("result"); - Room.this.channel = result.getString("channel"); - Room.this.roomId = result.getString("roomId"); - if (subscribeResponseListener != null) { - subscribeResponseListener.done(null, Room.this); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - - Room.this.kuzzle.addSubscription(Room.this.roomId, Room.this.id, Room.this); - - Room.this.kuzzle.addRoom(Room.this.channel, new EventListener() { - @Override - public void trigger(final Object... args) { - callAfterRenew(args[0]); - } - }); - - Room.this.dequeue(); - } - - @Override - public void onError(JSONObject arg) { - Room.this.subscribing = false; - Room.this.queue.clear(); - if (subscribeResponseListener != null) { - subscribeResponseListener.done(arg, null); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }).start(); - - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * Unsubscribes from Kuzzle. - * Stop listening immediately. If there is no listener left on that room, - * sends an unsubscribe request to Kuzzle, once - * pending subscriptions reaches 0, and only if there is still no listener on that room. - * We wait for pending subscriptions to finish to avoid unsubscribing while - * another subscription on that room is - * - * @return this - */ - public Room unsubscribe() { - if (!this.isReady()) { - this.queue.add(new Runnable() { - @Override - public void run() { - Room.this.unsubscribe(); - } - }); - return this; - } - - if (this.roomId == null) { - return this; - } - - try { - final JSONObject data = new JSONObject().put("body", new JSONObject().put("roomId", this.roomId)); - this.kuzzle.addHeaders(data, this.headers); - - this.kuzzle.removeRoom(Room.this.channel); - this.kuzzle.deleteSubscription(this.roomId, this.id); - - if (this.kuzzle.getSubscriptions(this.roomId) == null) { - final String roomId = this.roomId; - if (this.kuzzle.getPendingSubscriptions().isEmpty()) { - this.kuzzle.query(this.dataCollection.makeQueryArgs("realtime", "unsubscribe"), data); - } else { - final Timer timer = new Timer(UUID.randomUUID().toString()); - unsubscribeTask(timer, roomId, data).run(); - } - } - - this.roomId = null; - } - catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * Unsubscribe task timer task. - * - * @param timer the timer - * @param roomId the room id - * @param data the data - * @return the timer task - */ - protected TimerTask unsubscribeTask(final Timer timer, final String roomId, final JSONObject data) { - return new TimerTask() { - @Override - public void run() { - try { - if (Room.this.kuzzle.getPendingSubscriptions().isEmpty()) { - if (Room.this.kuzzle.getSubscriptions(roomId) == null) { - Room.this.kuzzle.query(Room.this.dataCollection.makeQueryArgs("realtime", "unsubscribe"), data); - } - } else { - timer.schedule(unsubscribeTask(timer, roomId, data), 100); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }; - } - - /** - * Linked data collection name getter - * - * @return linked data collection name - */ - public String getCollection() { - return collection; - } - - /** - * Subscription filters getter - * - * @return subscription filters - */ - public JSONObject getFilters() { - return filters; - } - - /** - * Subscription filters setter. - * renew must be called for this to take effect - * - * @param filters New subscription filters - * @return this - */ - public Room setFilters(final JSONObject filters) { - this.filters = filters; - return this; - } - - /** - * headers property getters - * - * @return headers value - */ - public JSONObject getHeaders() { - return this.headers; - } - - /** - * {@link #setHeaders(JSONObject, boolean)} - */ - public Room setHeaders(final JSONObject content) { - return this.setHeaders(content, false); - } - - /** - * Subscription headers setter - * - * @param content - new headers content - * @param replace - default: false = append the content, true = replace - * @return this - */ - public Room setHeaders(final JSONObject content, final boolean replace) { - if (this.headers == null) { - this.headers = new JSONObject(); - } - if (replace) { - this.headers = content; - } else { - if (content != null) { - try { - for (Iterator ite = content.keys(); ite.hasNext(); ) { - String key = (String) ite.next(); - this.headers.put(key, content.get(key)); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - return this; - } - - /** - * Gets volatile data. - * - * @return the volatile property - */ - public JSONObject getVolatile() { - return _volatile; - } - - /** - * Sets volatile metadata. - * - * @param _volatile New volatile data value - * @return this - */ - public Room setVolatile(final JSONObject _volatile) { - this._volatile = _volatile; - return this; - } - - /** - * subscribeToSelf property getter - * - * @return subscribeToSelf property value - */ - public boolean isSubscribeToSelf() { - return subscribeToSelf; - } - - /** - * subscribeToSelf property setter - * - * @param subscribeToSelf New subscribeToSelf value - * @return this - */ - public Room setSubscribeToSelf(final boolean subscribeToSelf) { - this.subscribeToSelf = subscribeToSelf; - return this; - } - - /** - * roomId property getter - * - * @return roomId property value - */ - public String getRoomId() { - return this.roomId; - } - - /** - * listener property getter - * - * @return listener property value - */ - public ResponseListener getListener() { - return this.listener; - } - - /** - * subscribeListener property getter - * @return subscribeListener property value - */ - public SubscribeListener getSubscribeListener() { - return doneListener; - } - - /** - * Runs all queued methods called while subscription was in progress - */ - protected void dequeue() { - if (this.queue.size() > 0) { - ExecutorService threadPool = Executors.newSingleThreadExecutor(); - - for(Runnable r: this.queue) { - threadPool.execute(r); - } - - threadPool.shutdown(); - - try { - threadPool.awaitTermination(1, TimeUnit.SECONDS); - } - catch (InterruptedException e) { - // do nothing - } - finally { - this.queue.clear(); - } - } - } - - private boolean isReady() { - return this.kuzzle.state == States.CONNECTED && !this.subscribing; - } -} diff --git a/src/main/java/io/kuzzle/sdk/core/RoomOptions.java b/src/main/java/io/kuzzle/sdk/core/RoomOptions.java deleted file mode 100644 index 2c1dbafd..00000000 --- a/src/main/java/io/kuzzle/sdk/core/RoomOptions.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.kuzzle.sdk.core; - -import org.json.JSONObject; - -import io.kuzzle.sdk.enums.Scope; -import io.kuzzle.sdk.enums.State; -import io.kuzzle.sdk.enums.Users; - -public class RoomOptions { - - private boolean subscribeToSelf = true; - private JSONObject _volatile = new JSONObject(); - private Scope scope = Scope.ALL; - private State state = State.DONE; - private Users users = Users.NONE; - - /** - * subscribeToSelf property getter - * - * @return subscribeToSelf property value - */ - public boolean isSubscribeToSelf() { - return subscribeToSelf; - } - - /** - * subscribeToSelf property setter - * - * @param subscribeToSelf New subscribeToSelf value - * @return this - */ - public RoomOptions setSubscribeToSelf(boolean subscribeToSelf) { - this.subscribeToSelf = subscribeToSelf; - - return this; - } - - /** - * volatile property getter - * @return volatile property value - */ - public JSONObject getVolatile() { - return _volatile; - } - - /** - * volatile property setter - * @param _volatile New volatile value - * @return this - */ - public RoomOptions setVolatile(JSONObject _volatile) { - this._volatile = _volatile; - - return this; - } - - /** - * scope property getter - * @return scope property value - */ - public Scope getScope() { - return scope; - } - - /** - * scope property setter - * @param scope New scope value - * @return this - */ - public RoomOptions setScope(Scope scope) { - this.scope = scope; - - return this; - } - - /** - * state property getter - * @return state property value - */ - public State getState() { - return state; - } - - /** - * state property setter - * @param state New state value - * @return this - */ - public RoomOptions setState(State state) { - this.state = state; - - return this; - } - - /** - * users property getter - * @return users property value - */ - public Users getUsers() { - return users; - } - - /** - * users property setter - * @param users New users value - * @return this - */ - public RoomOptions setUsers(Users users) { - this.users = users; - - return this; - } - -} diff --git a/src/main/java/io/kuzzle/sdk/enums/CollectionType.java b/src/main/java/io/kuzzle/sdk/enums/CollectionType.java deleted file mode 100644 index 5d7865ea..00000000 --- a/src/main/java/io/kuzzle/sdk/enums/CollectionType.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.kuzzle.sdk.enums; - -public enum CollectionType { - STORED, - REALTIME, - ALL -} diff --git a/src/main/java/io/kuzzle/sdk/enums/Event.java b/src/main/java/io/kuzzle/sdk/enums/Event.java deleted file mode 100644 index 6c9d7fb2..00000000 --- a/src/main/java/io/kuzzle/sdk/enums/Event.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.kuzzle.sdk.enums; - -/** - * The enum Event type. - */ -public enum Event { - disconnected, - reconnected, - connected, - error, - tokenExpired, - loginAttempt, - offlineQueuePush, - offlineQueuePop -} diff --git a/src/main/java/io/kuzzle/sdk/enums/Mode.java b/src/main/java/io/kuzzle/sdk/enums/Mode.java deleted file mode 100644 index 8f3e76a7..00000000 --- a/src/main/java/io/kuzzle/sdk/enums/Mode.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.kuzzle.sdk.enums; - -public enum Mode { - AUTO, MANUAL -} diff --git a/src/main/java/io/kuzzle/sdk/enums/Policies.java b/src/main/java/io/kuzzle/sdk/enums/Policies.java deleted file mode 100644 index 4ace1803..00000000 --- a/src/main/java/io/kuzzle/sdk/enums/Policies.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.kuzzle.sdk.enums; - -public enum Policies { - allowed, denied, conditional -} diff --git a/src/main/java/io/kuzzle/sdk/enums/Scope.java b/src/main/java/io/kuzzle/sdk/enums/Scope.java deleted file mode 100644 index 04b1cc9e..00000000 --- a/src/main/java/io/kuzzle/sdk/enums/Scope.java +++ /dev/null @@ -1,9 +0,0 @@ -package io.kuzzle.sdk.enums; - -public enum Scope { - IN, - OUT, - ALL, - NONE, - UNKNOWN -} diff --git a/src/main/java/io/kuzzle/sdk/enums/State.java b/src/main/java/io/kuzzle/sdk/enums/State.java deleted file mode 100644 index eb66eb1f..00000000 --- a/src/main/java/io/kuzzle/sdk/enums/State.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.kuzzle.sdk.enums; - -public enum State { - PENDING, - ALL, - DONE -} diff --git a/src/main/java/io/kuzzle/sdk/enums/Users.java b/src/main/java/io/kuzzle/sdk/enums/Users.java deleted file mode 100644 index b8f38fa5..00000000 --- a/src/main/java/io/kuzzle/sdk/enums/Users.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.kuzzle.sdk.enums; - -public enum Users { - IN, - OUT, - ALL, - NONE -} diff --git a/src/main/java/io/kuzzle/sdk/listeners/EventListener.java b/src/main/java/io/kuzzle/sdk/listeners/EventListener.java deleted file mode 100644 index 9661803e..00000000 --- a/src/main/java/io/kuzzle/sdk/listeners/EventListener.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.kuzzle.sdk.listeners; - -/** - * The interface Event listener. - */ -public interface EventListener { - - /** - * Trigger. - * - * @param args the args - */ - void trigger(Object ... args); - -} diff --git a/src/main/java/io/kuzzle/sdk/listeners/OnConnectionEvent.java b/src/main/java/io/kuzzle/sdk/listeners/OnConnectionEvent.java deleted file mode 100644 index 3afa1527..00000000 --- a/src/main/java/io/kuzzle/sdk/listeners/OnConnectionEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.kuzzle.sdk.listeners; - -import org.json.JSONObject; - -public interface OnConnectionEvent { - void onSuccess(JSONObject success); - void onError(JSONObject error); -} diff --git a/src/main/java/io/kuzzle/sdk/listeners/OnQueryDoneListener.java b/src/main/java/io/kuzzle/sdk/listeners/OnQueryDoneListener.java deleted file mode 100644 index 82412433..00000000 --- a/src/main/java/io/kuzzle/sdk/listeners/OnQueryDoneListener.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.kuzzle.sdk.listeners; - -import org.json.JSONObject; - -public interface OnQueryDoneListener { - void onSuccess(JSONObject response); - void onError(JSONObject error); -} diff --git a/src/main/java/io/kuzzle/sdk/listeners/ResponseListener.java b/src/main/java/io/kuzzle/sdk/listeners/ResponseListener.java deleted file mode 100644 index 3972da96..00000000 --- a/src/main/java/io/kuzzle/sdk/listeners/ResponseListener.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.kuzzle.sdk.listeners; - -import org.json.JSONObject; - -/** - * The interface Response listener. - */ -public interface ResponseListener { - /** - * On success. - * - * @param response Raw Kuzzle API response - */ - void onSuccess(T response); - - /** - * On error. - * - * @param error Raw Kuzzle API error content - */ - void onError(JSONObject error); -} diff --git a/src/main/java/io/kuzzle/sdk/listeners/SubscribeListener.java b/src/main/java/io/kuzzle/sdk/listeners/SubscribeListener.java deleted file mode 100644 index 48e46105..00000000 --- a/src/main/java/io/kuzzle/sdk/listeners/SubscribeListener.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.kuzzle.sdk.listeners; - -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.List; - -import io.kuzzle.sdk.core.Room; - -public class SubscribeListener { - private JSONObject error; - private Room room; - private List> cbs = new ArrayList<>(); - - public void onDone(ResponseListener cb) { - if (this.error != null) { - cb.onError(this.error); - } else if (this.room != null) { - cb.onSuccess(this.room); - } else { - this.cbs.add(cb); - } - } - - public SubscribeListener done(JSONObject error, Room room) { - this.error = error; - this.room = room; - - for (ResponseListener cb : cbs) { - if (this.error != null) { - cb.onError(this.error); - } else if (this.room != null) { - cb.onSuccess(this.room); - } - } - return this; - } - - public JSONObject getError() { - return error; - } - - public Room getRoom() { - return room; - } -} diff --git a/src/main/java/io/kuzzle/sdk/responses/KuzzleList.java b/src/main/java/io/kuzzle/sdk/responses/KuzzleList.java deleted file mode 100644 index 19103c79..00000000 --- a/src/main/java/io/kuzzle/sdk/responses/KuzzleList.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.kuzzle.sdk.responses; - -import java.util.List; - -public interface KuzzleList { - public List getDocuments(); - public long getTotal(); -} diff --git a/src/main/java/io/kuzzle/sdk/responses/NotificationResponse.java b/src/main/java/io/kuzzle/sdk/responses/NotificationResponse.java deleted file mode 100644 index 522eb911..00000000 --- a/src/main/java/io/kuzzle/sdk/responses/NotificationResponse.java +++ /dev/null @@ -1,142 +0,0 @@ -package io.kuzzle.sdk.responses; - -import org.json.JSONException; -import org.json.JSONObject; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.enums.Scope; -import io.kuzzle.sdk.enums.State; -import io.kuzzle.sdk.enums.Users; - -public class NotificationResponse { - private int status; - private String index; - private String collection; - private String controller; - private String action; - private State state; - private Scope scope; - private Users users; - private JSONObject _volatile; - private String requestId; - private Document document; - private JSONObject result; - - /** - * Response notification representation - * @see SDK Reference - * @param kuzzle Kuzzle instance to attach - * @param object Raw Kuzzle API notification - */ - public NotificationResponse(final Kuzzle kuzzle, final JSONObject object) { - try { - this.status = object.getInt("status"); - this.index = object.getString("index"); - this.collection = object.getString("collection"); - this.controller = object.getString("controller"); - this.action = object.getString("action"); - this.state = (object.isNull("state") ? null : State.valueOf(object.getString("state").toUpperCase())); - this._volatile = object.isNull("volatile") ? new JSONObject() : object.getJSONObject("volatile"); - this.requestId = object.isNull("requestId") ? null : object.getString("requestId"); - this.result = (object.isNull("result") ? null : object.getJSONObject("result")); - this.scope = (object.isNull("scope") ? null : Scope.valueOf(object.getString("scope").toUpperCase())); - this.users = (object.isNull("user") ? null : Users.valueOf(object.getString("user").toUpperCase())); - if (!object.getJSONObject("result").isNull("_source")) { - JSONObject content = object.getJSONObject("result"); - String id = content.getString("_id"); - JSONObject meta = content.isNull("_meta") ? new JSONObject() : content.getJSONObject("_meta"); - content.remove("_id"); - content.remove("_meta"); - this.document = new Document(new Collection(kuzzle, this.collection, this.index), id, content, meta); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * @return Notification status value - */ - public int getStatus() { - return status; - } - - /** - * @return Impacted data index value - */ - public String getIndex() { - return index; - } - - /** - * @return Impacted data collection value - */ - public String getCollection() { - return collection; - } - - /** - * @return Invoked Kuzzle API controller - */ - public String getController() { - return controller; - } - - /** - * @return Executed API controller action - */ - public String getAction() { - return action; - } - - /** - * @return Notification state - */ - public State getState() { - return state; - } - - /** - * @return Notification scope - */ - public Scope getScope() { - return scope; - } - - /** - * @return Notification volatile data - */ - public JSONObject getVolatile() { - return _volatile; - } - - /** - * @return Origin request unique ID - */ - public String getRequestId() { - return requestId; - } - - /** - * @return Notification content - */ - public Document getDocument() { - return document; - } - - /** - * @return Notification raw content - */ - public JSONObject getResult() { - return result; - } - - /** - * @return Notification users state - */ - public Users getUsers() { - return users; - } -} diff --git a/src/main/java/io/kuzzle/sdk/responses/SearchResult.java b/src/main/java/io/kuzzle/sdk/responses/SearchResult.java deleted file mode 100644 index a49eba94..00000000 --- a/src/main/java/io/kuzzle/sdk/responses/SearchResult.java +++ /dev/null @@ -1,191 +0,0 @@ -package io.kuzzle.sdk.responses; - - - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.List; - -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; - -public class SearchResult implements KuzzleList { - private Collection collection; - private long total; - private List documents; - private JSONObject aggregations; - private Options options; - private JSONObject filters; - private long fetchedDocument; - - public SearchResult(Collection collection, long total, List documents) { - this(collection, total, documents, null, new Options(), new JSONObject(), null); - } - - public SearchResult(Collection collection, long total, List documents, JSONObject aggregations) { - this(collection, total, documents, aggregations, new Options(), new JSONObject(), null); - } - - public SearchResult(Collection collection, long total, List documents, JSONObject aggregations, Options options, JSONObject filters) { - this(collection, total, documents, aggregations, options, filters, null); - } - - public SearchResult(Collection collection, long total, List documents, JSONObject aggregations, Options options, JSONObject filters, SearchResult previous) { - this.collection = collection; - this.total = total; - this.documents = documents; - this.aggregations = aggregations; - this.options = options; - this.filters = filters; - this.fetchedDocument = previous != null ? documents.size() + previous.getFetchedDocument() : documents.size(); - } - - /** - * @return Fetched documents list - */ - public List getDocuments() { - return documents; - } - - /** - * @return Total number of fetchable documents - */ - public long getTotal() { - return total; - } - - /** - * @return Search request aggregations parameters - */ - public JSONObject getAggregations() { - return aggregations; - } - - /** - * @return Number of fetched documents so far - */ - public long getFetchedDocument() { - return fetchedDocument; - } - - /** - * @return Parent data collection - */ - public Collection getCollection() { - return collection; - } - - /** - * @return Search request options - */ - public Options getOptions() { - return options; - } - - /** - * @return Search request filters - */ - public JSONObject getFilters() { - return filters; - } - - /** - * Fetches the next batch of documents - * @param listener Response callback listener - */ - public void fetchNext(ResponseListener listener) { - JSONObject filters; - Options options; - - try { - options = new Options(this.options); - } catch (JSONException e) { - throw new RuntimeException(e); - } - options.setPrevious(this); - - // retrieve next results with scroll if original search use it - if (options.getScrollId() != null) { - if (this.fetchedDocument >= this.getTotal()) { - listener.onSuccess(null); - - return; - } - - if (options.getFrom() != null) { - options.setFrom(null); - } - - if (options.getSize() != null) { - options.setSize(null); - } - - this.collection.scroll(options.getScrollId(), options, this.filters, listener); - - return; - } - - // retrieve next results using ES's search_after - if (options.getSize() != null && this.filters.has("sort")) { - if (this.fetchedDocument >= this.getTotal()) { - listener.onSuccess(null); - - return; - } - - if (options.getFrom() != null) { - options.setFrom(null); - } - - try { - JSONArray searchAfter = new JSONArray(); - - for (int i = 0; i < this.filters.getJSONArray("sort").length(); i++) { - Document doc = this.getDocuments().get(this.getDocuments().size() - 1); - searchAfter.put(doc.getContent().get(this.filters.getJSONArray("sort").getJSONObject(i).keys().next())); - } - - this.filters.put("search_after", searchAfter); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - this.collection.search(this.filters, options, listener); - - return; - } - - // retrieve next results with from/size if original search use it - if (options.getFrom() != null && options.getSize() != null) { - try { - filters = new JSONObject(this.filters.toString()); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - options.setFrom(options.getFrom() + options.getSize()); - - if (options.getFrom() >= this.getTotal()) { - listener.onSuccess(null); - - return; - } - - this.collection.search(filters, options, listener); - - return; - } - - JSONObject error; - try { - error = new JSONObject("Unable to retrieve next results from search: missing scrollId or from/size params"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - listener.onError(error); - } -} diff --git a/src/main/java/io/kuzzle/sdk/responses/SecurityDocumentList.java b/src/main/java/io/kuzzle/sdk/responses/SecurityDocumentList.java deleted file mode 100644 index 423f6977..00000000 --- a/src/main/java/io/kuzzle/sdk/responses/SecurityDocumentList.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.kuzzle.sdk.responses; - - -import java.util.List; - -import io.kuzzle.sdk.security.AbstractSecurityDocument; -import io.kuzzle.sdk.util.Scroll; - -public class SecurityDocumentList implements KuzzleList { - private List documents; - private long total; - private Scroll scroll; - - public SecurityDocumentList(List roles, long total, Scroll scroll) { - this.documents = roles; - this.total = total; - this.scroll = scroll; - } - - public SecurityDocumentList(List roles, long total) { - this(roles, total, new Scroll()); - } - - public List getDocuments() { - return documents; - } - - public long getTotal() { - return total; - } - - public Scroll getScroll() { return scroll; } -} diff --git a/src/main/java/io/kuzzle/sdk/responses/TokenValidity.java b/src/main/java/io/kuzzle/sdk/responses/TokenValidity.java deleted file mode 100644 index b86e7992..00000000 --- a/src/main/java/io/kuzzle/sdk/responses/TokenValidity.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.kuzzle.sdk.responses; - -import java.util.Date; - -public class TokenValidity { - private boolean valid; - private String state; - private Date expiresAt; - - public boolean isValid() { - return valid; - } - - public void setValid(boolean valid) { - this.valid = valid; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public Date getExpiresAt() { - return expiresAt; - } - - public void setExpiresAt(Date expiresAt) { - this.expiresAt = expiresAt; - } -} diff --git a/src/main/java/io/kuzzle/sdk/security/AbstractSecurityDocument.java b/src/main/java/io/kuzzle/sdk/security/AbstractSecurityDocument.java deleted file mode 100644 index bd8032b5..00000000 --- a/src/main/java/io/kuzzle/sdk/security/AbstractSecurityDocument.java +++ /dev/null @@ -1,226 +0,0 @@ -package io.kuzzle.sdk.security; - - - -import org.json.JSONException; -import org.json.JSONObject; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -/** - * Base class for the Role, Profile and User classes - */ -public class AbstractSecurityDocument { - protected final Kuzzle kuzzle; - protected final Security kuzzleSecurity; - protected String deleteActionName; - protected String updateActionName; - public final String id; - public JSONObject content; - public JSONObject meta; - - /** - * Instantiates a new Abstract kuzzle security document. - * - * @param kuzzle Kuzzle instance to link - * @param id Security document unique ID - * @param content Security document content - * @throws JSONException - */ - public AbstractSecurityDocument(final Kuzzle kuzzle, final String id, final JSONObject content, final JSONObject meta) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Cannot initialize with a null ID"); - } - - this.kuzzle = kuzzle; - this.kuzzleSecurity = kuzzle.security; - this.id = id; - - if (content != null) { - setContent(content); - } else { - this.content = new JSONObject(); - } - - if (meta != null) { - this.meta = new JSONObject(meta.toString()); - } - } - - /** - * Sets the content of this object - * - * @param content New content - * @return this - * @throws JSONException - */ - public AbstractSecurityDocument setContent(final JSONObject content) throws JSONException { - if (content == null) { - throw new IllegalArgumentException("AbstractSecurityDocument.setContent: cannot set null content"); - } - - this.content = new JSONObject(content.toString()); - - return this; - } - - /** - * Serializes this object to a plain-old JSON object - * - * @return The serialized version of this object - * @throws JSONException - */ - public JSONObject serialize() throws JSONException { - JSONObject data; - - data = new JSONObject() - .put("_id", this.id) - .put("body", content); - - return data; - } - - /** - * Delete this role/profile/user from Kuzzle - * - * @param options Optional configuration - * @param listener Optional response callback - * @throws JSONException - */ - public void delete(final Options options, final ResponseListener listener) throws JSONException { - JSONObject data = new JSONObject().put("_id", this.id); - - if (listener != null) { - this.kuzzle.query(kuzzleSecurity.buildQueryArgs(this.deleteActionName), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result").getString("_id")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(kuzzleSecurity.buildQueryArgs(this.deleteActionName), data, options); - } - } - - /** - * {@link #delete(Options, ResponseListener)} - */ - public void delete(final ResponseListener listener) throws JSONException { - this.delete(null, listener); - } - - /** - * {@link #delete(Options, ResponseListener)} - */ - public void delete(final Options options) throws JSONException { - this.delete(options, null); - } - - /** - * {@link #delete(Options, ResponseListener)} - */ - public void delete() throws JSONException { - this.delete(null, null); - } - - /** - * Getter for the "id" property - * - * @return the document id - */ - public String getId() { - return this.id; - } - - /** - * Getter for the "content" property - * - * @return the document content - */ - public JSONObject getContent() { - return this.content; - } - - /** - * Getter for the "meta" property - * - * @return the document metadata - */ - public JSONObject getMeta() { - return this.meta; - } - - /** - * {@link #update(JSONObject, Options, ResponseListener)} - */ - public AbstractSecurityDocument update(final JSONObject content) throws JSONException { - return this.update(content, null, null); - } - - /** - * {@link #update(JSONObject, Options, ResponseListener)} - */ - public AbstractSecurityDocument update(final JSONObject content, final Options options) throws JSONException { - return this.update(content, options, null); - } - - /** - * {@link #update(JSONObject, Options, ResponseListener)} - */ - public AbstractSecurityDocument update(final JSONObject content, final ResponseListener listener) throws JSONException { - return this.update(content, null, listener); - } - - /** - * Perform a partial update on this object - * - * @param content Content used to update the object - * @param options Request optional parameters - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public AbstractSecurityDocument update(final JSONObject content, final Options options, final ResponseListener listener) throws JSONException { - JSONObject data = new JSONObject() - .put("_id", this.id) - .put("body", content); - - if (listener != null) { - this.kuzzle.query(kuzzleSecurity.buildQueryArgs(this.updateActionName), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject updatedContent = response.getJSONObject("result").getJSONObject("_source"); - AbstractSecurityDocument.this.setContent(updatedContent); - listener.onSuccess(AbstractSecurityDocument.this); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(kuzzleSecurity.buildQueryArgs(this.updateActionName), data, options); - } - - return this; - } -} diff --git a/src/main/java/io/kuzzle/sdk/security/Profile.java b/src/main/java/io/kuzzle/sdk/security/Profile.java deleted file mode 100644 index 1cbded45..00000000 --- a/src/main/java/io/kuzzle/sdk/security/Profile.java +++ /dev/null @@ -1,211 +0,0 @@ -package io.kuzzle.sdk.security; - - - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Arrays; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -/** - * This class handles profiles management in Kuzzle - */ -public class Profile extends AbstractSecurityDocument { - private ArrayList policies = new ArrayList<>(); - - /** - * Instantiates a new Kuzzle profile. - * - * @param kuzzle Kuzzle instance to attach - * @param id Profile unique ID - * @param content Profile content - * @param meta Profile metadata - * @throws JSONException - */ - public Profile(final Kuzzle kuzzle, final String id, final JSONObject content, final JSONObject meta) throws JSONException { - super(kuzzle, id, null, meta); - this.deleteActionName = "deleteProfile"; - this.updateActionName = "updateProfile"; - - if (content != null) { - this.content = new JSONObject(content.toString()); - - if (content.has("policies")) { - JSONArray arr = content.getJSONArray("policies"); - - for (int i = 0; i < arr.length(); i++) { - this.policies.add(arr.getJSONObject(i)); - } - - this.content.remove("policies"); - } - } - } - - /** - * Save this profile in Kuzzle - * - * @param options Request optional arguments - * @param listener Callback listener - * @return this - * @throws JSONException - */ - public Profile save(final Options options, final ResponseListener listener) throws JSONException { - JSONObject data; - - if (this.policies.size() == 0) { - throw new IllegalArgumentException("Cannot save the profile " + this.id + ": no policy defined"); - } - - data = this.serialize(); - - if (listener != null) { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceProfile"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - listener.onSuccess(Profile.this); - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceProfile"), data, options); - } - - return this; - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Profile save(final ResponseListener listener) throws JSONException { - return this.save(null, listener); - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Profile save(final Options options) throws JSONException { - return this.save(options, null); - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Profile save() throws JSONException { - return this.save(null, null); - } - - /** - * Add a new role to the list of allowed roles of this profile - * - * @param policy Policy to add to this profile - * @return this - * @throws IllegalArgumentException - */ - public Profile addPolicy(final JSONObject policy) throws IllegalArgumentException { - if (!policy.has("roleId")) { - throw new IllegalArgumentException("The policy must have, at least, a roleId set."); - } - - this.policies.add(policy); - return this; - } - - /** - * Add a new policy to the list of policies of this profile via its roleId - * - * @param roleId Name of the role to add to this profile - * @return this - */ - public Profile addPolicy(final String roleId) { - JSONObject policy = new JSONObject(); - try { - policy.put("roleId", roleId); - } catch (JSONException e) { - throw new RuntimeException(e); - } - this.policies.add(policy); - return this; - } - - /** - * Replace the current policies list with a new one - * - * @param policies New policies list - * @return this - * @throws IllegalArgumentException - */ - public Profile setPolicies(final JSONObject[] policies) throws IllegalArgumentException { - for(JSONObject policy : policies) { - if (!policy.has("roleId")) { - throw new IllegalArgumentException("All pocicies must have at least a roleId set."); - } - } - - this.policies = new ArrayList<>(Arrays.asList(policies)); - - return this; - } - - /** - * Replace the current policies list with a new one via its rolesIds - * - * @param roleIds New roles identifiers list - * @return this - */ - public Profile setPolicies(final String[] roleIds) { - this.policies.clear(); - - try { - for (String roleId : roleIds) { - this.policies.add(new JSONObject().put("roleId", roleId)); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * Serialize the content of this object to a JSON Object - * @return a serialized version of this object - * @throws JSONException - */ - public JSONObject serialize() throws JSONException { - JSONObject - data = new JSONObject(), - content = new JSONObject(this.content.toString()); - - if (this.policies.size() > 0) { - content.put("policies", new JSONArray(this.policies)); - } - - data - .put("_id", this.id) - .put("body", content); - - return data; - } - - /** - * Return the list of the policies assigned to this profile - * - * @return a JSONArray of policies objects - */ - public JSONObject[] getPolicies() { - return this.policies.toArray(new JSONObject[0]); - } -} diff --git a/src/main/java/io/kuzzle/sdk/security/Role.java b/src/main/java/io/kuzzle/sdk/security/Role.java deleted file mode 100644 index cde4b343..00000000 --- a/src/main/java/io/kuzzle/sdk/security/Role.java +++ /dev/null @@ -1,83 +0,0 @@ -package io.kuzzle.sdk.security; - - - -import org.json.JSONException; -import org.json.JSONObject; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -/** - * This class handles roles management in Kuzzle - */ -public class Role extends AbstractSecurityDocument { - /** - * Instantiates a new Kuzzle role. - * - * @param kuzzle Kuzzle instance to attach - * @param id Role unique identifier - * @param content Role content - * @param meta Role metadata - * @throws JSONException - */ - public Role(final Kuzzle kuzzle, final String id, final JSONObject content, final JSONObject meta) throws JSONException { - super(kuzzle, id, content, meta); - this.deleteActionName = "deleteRole"; - this.updateActionName = "updateRole"; - } - - /** - * Save this role in Kuzzle - * - * @param options Request optional configuration - * @param listener Optional callback listener - * @return this - * @throws JSONException - */ - public Role save(final Options options, final ResponseListener listener) throws JSONException { - JSONObject data = this.serialize(); - - if (listener != null) { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceRole"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - listener.onSuccess(Role.this); - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceRole"), data, options); - } - - return this; - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Role save(final ResponseListener listener) throws JSONException { - return this.save(null, listener); - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Role save(final Options options) throws JSONException { - return this.save(options, null); - } - - /** - * {@link #save(Options, ResponseListener)} - */ - public Role save() throws JSONException { - return this.save(null, null); - } -} diff --git a/src/main/java/io/kuzzle/sdk/security/Security.java b/src/main/java/io/kuzzle/sdk/security/Security.java deleted file mode 100644 index d7bae736..00000000 --- a/src/main/java/io/kuzzle/sdk/security/Security.java +++ /dev/null @@ -1,1847 +0,0 @@ -package io.kuzzle.sdk.security; - - - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Arrays; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Policies; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.SecurityDocumentList; -import io.kuzzle.sdk.util.Scroll; - -/** - * Kuzzle security API - */ -public class Security { - private final Kuzzle kuzzle; - - /** - * Instantiates a new Kuzzle security instance - * - * @param kuzzle Kuzzle instance to attach - */ - public Security(final Kuzzle kuzzle) { - this.kuzzle = kuzzle; - } - - /** - * Helper function meant to easily build the first Kuzzle.query() argument - * - * @param action Security controller action name - * @return Kuzzle.query() 1st argument object - * @throws JSONException - */ - protected Kuzzle.QueryArgs buildQueryArgs(final String controller, final String action) throws JSONException { - io.kuzzle.sdk.core.Kuzzle.QueryArgs args = new io.kuzzle.sdk.core.Kuzzle.QueryArgs(); - args.action = action; - args.controller = "security"; - - if (controller != null) { - args.controller = controller; - } - return args; - } - - protected Kuzzle.QueryArgs buildQueryArgs(final String action) throws JSONException { - return buildQueryArgs(null, action); - } - - /** - * Retrieves a single Role using its unique Role ID - * - * @param id Unique role ID - * @param options Optional query arguments - * @param listener Response callback listener - */ - public void fetchRole(final String id, Options options, final ResponseListener listener) { - JSONObject data; - - if (id == null) { - throw new IllegalArgumentException("Security.fetchRole: a role ID is required"); - } - - if (listener == null) { - throw new IllegalArgumentException("Security.fetchRole: a listener is required"); - } - - try { - data = new JSONObject().put("_id", id); - this.kuzzle.query(buildQueryArgs("getRole"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - listener.onSuccess(new Role(Security.this.kuzzle, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #fetchRole(String, Options, ResponseListener)} - */ - public void fetchRole(final String id, final ResponseListener listener) { - fetchRole(id, null, listener); - } - - - /** - * Executes a search on roles using a set of filters - * - * @param filters Search filters (see ElasticSearch filters) - * @param options Optional query arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void searchRoles(final JSONObject filters, final Options options, final ResponseListener listener) throws JSONException { - if (filters == null) { - throw new IllegalArgumentException("Security.searchRoles: filters cannot be null"); - } - - if (listener == null) { - throw new IllegalArgumentException("Security.searchRoles: a callback listener is required"); - } - - JSONObject data = new JSONObject().put("body", filters); - - this.kuzzle.query(buildQueryArgs("searchRoles"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - JSONArray documents = result.getJSONArray("hits"); - int documentsLength = documents.length(); - ArrayList roles = new ArrayList<>(); - - for (int i = 0; i < documentsLength; i++) { - JSONObject document = documents.getJSONObject(i); - roles.add(new Role(Security.this.kuzzle, document.getString("_id"), document.getJSONObject("_source"), document.getJSONObject("_meta"))); - } - - listener.onSuccess(new SecurityDocumentList(roles, result.getLong("total"))); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - - /** - * {@link #searchRoles(JSONObject, Options, ResponseListener)} - */ - public void searchRoles(final JSONObject filters, final ResponseListener listener) throws JSONException { - searchRoles(filters, null, listener); - } - - /** - * Create a new role in Kuzzle. - * If the same role already exists: throw an error by default - * (see the replaceIfExist request optional argument) - * - * @param id New role ID - * @param content New role rights definitions - * @param options Request optional parameters - * @param listener Response callback listener - * @throws JSONException - */ - public void createRole(final String id, final JSONObject content, Options options, final ResponseListener listener) throws JSONException { - String action = "createRole"; - - if (id == null || content == null) { - throw new IllegalArgumentException("Security.createRole: cannot create a role without an ID or a content"); - } - - JSONObject data = new JSONObject().put("_id", id).put("body", content); - - if (options != null && options.isReplaceIfExist()) { - action = "createOrReplaceRole"; - } - - if (listener != null) { - this.kuzzle.query(buildQueryArgs(action), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - listener.onSuccess(new Role(Security.this.kuzzle, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs(action), data, options); - } - } - - /** - * {@link #createRole(String, JSONObject, Options, ResponseListener)} - */ - public void createRole(final String id, final JSONObject content, final ResponseListener listener) throws JSONException { - createRole(id, content, null, listener); - } - - /** - * {@link #createRole(String, JSONObject, Options, ResponseListener)} - */ - public void createRole(final String id, final JSONObject content, Options options) throws JSONException { - createRole(id, content, options, null); - } - - /** - * {@link #createRole(String, JSONObject, Options, ResponseListener)} - */ - public void createRole(final String id, final JSONObject content) throws JSONException { - createRole(id, content, null, null); - } - - /** - * Delete a role from Kuzzle - * - * @param id ID of the role to delete - * @param options Request optional arguments - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Security deleteRole(final String id, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.deleteRole: cannot delete role without an ID"); - } - - JSONObject data = new JSONObject().put("_id", id); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs("deleteRole"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result").getString("_id")); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs("deleteRole"), data, options); - } - - return this; - } - - /** - * {@link #deleteRole(String, Options, ResponseListener)} - */ - public Security deleteRole(final String id, final ResponseListener listener) throws JSONException { - return deleteRole(id, null, listener); - } - - /** - * {@link #deleteRole(String, Options, ResponseListener)} - */ - public Security deleteRole(final String id, final Options options) throws JSONException { - return deleteRole(id, options, null); - } - - /** - * {@link #deleteRole(String, Options, ResponseListener)} - */ - public Security deleteRole(final String id) throws JSONException { - return deleteRole(id, null, null); - } - - /** - * Update a role's content - * - * @param id ID of the role to update - * @param content Role content to update - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Security updateRole(final String id, final JSONObject content, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.updateRole: cannot update role without an ID"); - } - - JSONObject data = new JSONObject().put("_id", id); - data.put("body", content); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs("updateRole"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(new Role(Security.this.kuzzle, response.getJSONObject("result").getString("_id"), response.getJSONObject("result").getJSONObject("_source"), response.getJSONObject("result").getJSONObject("_meta"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs("updateRole"), data, options); - } - - return this; - } - - /** - * {@link #updateRole(String, JSONObject, Options, ResponseListener)} - */ - public Security updateRole(final String id, final JSONObject content, final ResponseListener listener) throws JSONException { - return updateRole(id, content, null, listener); - } - - /** - * {@link #updateRole(String, JSONObject, Options, ResponseListener)} - */ - public Security updateRole(final String id, final JSONObject content, final Options options) throws JSONException { - return updateRole(id, content, options, null); - } - - /** - * {@link #updateRole(String, JSONObject, Options, ResponseListener)} - */ - public Security updateRole(final String id, final JSONObject content) throws JSONException { - return updateRole(id, content, null, null); - } - - /** - * Instantiate a new Role object. - * Does not automatically create it in Kuzzle - * - * @param id Role unique identifier - * @param content Role content - * @param meta Role metadata - * @return new Role object - * @throws JSONException - */ - public Role role(final String id, final JSONObject content, final JSONObject meta) throws JSONException { - return new Role(this.kuzzle, id, content, meta); - } - - /** - * {@link #role(String, JSONObject, JSONObject)} - */ - public Role role(final String id, final JSONObject content) throws JSONException { - return new Role(this.kuzzle, id, content, null); - } - - /** - * {@link #role(String, JSONObject, JSONObject)} - */ - public Role role(final String id) throws JSONException { - return new Role(this.kuzzle, id, null, null); - } - - /** - * Get a specific profile from kuzzle - * - * @param id ID of the profile to retrieve - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void fetchProfile(final String id, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.fetchProfile: cannot get 'null' profile"); - } - - if (listener == null) { - throw new IllegalArgumentException("Security.fetchProfile: a listener callback is required"); - } - - JSONObject data = new JSONObject().put("_id", id); - - this.kuzzle.query(buildQueryArgs("getProfile"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - JSONArray formattedPolicies = new JSONArray(); - JSONArray policies = result.getJSONObject("_source").getJSONArray("policies"); - - for (int i = 0; i < policies.length(); i++) { - JSONObject formattedPolicy = new JSONObject() - .put("roleId", policies.getJSONObject(i).getString("roleId")); - if (((JSONObject) policies.get(i)).has("restrictedTo")) { - formattedPolicy.put("restrictedTo", policies.getJSONObject(i).getJSONArray("restrictedTo")); - } - if (((JSONObject) policies.get(i)).has("allowInternalIndex")) { - formattedPolicy.put("allowInternalIndex", policies.getJSONObject(i).getBoolean("allowInternalIndex")); - } - formattedPolicies.put(formattedPolicy); - } - - result.getJSONObject("_source").remove("policies"); - result.getJSONObject("_source").put("policies", formattedPolicies); - - listener.onSuccess(new Profile(Security.this.kuzzle, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - - /** - * {@link #fetchProfile(String, Options, ResponseListener)} - */ - public void fetchProfile(final String id, final ResponseListener listener) throws JSONException { - fetchProfile(id, null, listener); - } - - /** - * Executes a search on profiles according to a set of filters - * - * @param filters Search filters - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void searchProfiles(JSONObject filters, final Options options, final ResponseListener listener) throws JSONException { - if (filters == null) { - throw new IllegalArgumentException("Security.searchProfiles: cannot perform a search on null filters"); - } - - if (listener == null) { - throw new IllegalArgumentException("Security.searchProfiles: a listener callback is required"); - } - - JSONObject data = new JSONObject().put("body", filters); - - this.kuzzle.query(buildQueryArgs("searchProfiles"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - JSONArray documents = result.getJSONArray("hits"); - int documentsLength = documents.length(); - ArrayList profiles = new ArrayList<>(); - - for (int i = 0; i < documentsLength; i++) { - JSONObject document = documents.getJSONObject(i); - profiles.add(new Profile(Security.this.kuzzle, document.getString("_id"), document.getJSONObject("_source"), document.getJSONObject("_meta"))); - } - - Scroll scroll = new Scroll(); - - if (result.has("scrollId")) { - scroll.setScrollId(result.getString("scrollId")); - } - - listener.onSuccess(new SecurityDocumentList(profiles, result.getLong("total"), scroll)); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - - /** - * {@link #searchProfiles(JSONObject, Options, ResponseListener)} - */ - public void searchProfiles(JSONObject filters, final ResponseListener listener) throws JSONException { - searchProfiles(filters, null, listener); - } - - /** - * Create a new profile in Kuzzle. - * Throws an error if the profile already exists, unless - * "replaceIfExists" is set to true in request options - * - * @param id ID of the new profile - * @param policies List of policies attached to the new profile - * @param options Request optional arguments - * @param listener Callback lisener - * @throws JSONException - */ - public void createProfile(final String id, final JSONObject[] policies, final Options options, final ResponseListener listener) throws JSONException { - String action = "createProfile"; - - if (id == null || policies == null) { - throw new IllegalArgumentException("Security.createProfile: cannot create a profile with null ID or policies"); - } - - JSONObject data = new JSONObject() - .put("_id", id) - .put("body", new JSONObject().put("policies", new JSONArray(Arrays.asList(policies)))); - - if (options != null && options.isReplaceIfExist()) { - action = "createOrReplaceProfile"; - } - - if (listener != null) { - this.kuzzle.query(buildQueryArgs(action), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - listener.onSuccess(new Profile(Security.this.kuzzle, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs(action), data, options); - } - } - - /** - * {@link #createProfile(String, JSONObject[], Options, ResponseListener)} - */ - public void createProfile(final String id, final JSONObject[] policies, final Options options) throws JSONException { - createProfile(id, policies, options, null); - } - - /** - * {@link #createProfile(String, JSONObject[], Options, ResponseListener)} - */ - public void createProfile(final String id, final JSONObject[] policies, final ResponseListener listener) throws JSONException { - createProfile(id, policies, null, listener); - } - - /** - * {@link #createProfile(String, JSONObject[], Options, ResponseListener)} - */ - public void createProfile(final String id, final JSONObject[] policies) throws JSONException { - createProfile(id, policies, null, null); - } - - /** - * Delete a profile from Kuzzle - * - * @param id ID of the profile to delete - * @param options Request optional arguments - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Security deleteProfile(final String id, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.deleteProfile: cannot delete a profile with ID null"); - } - - JSONObject data = new JSONObject().put("_id", id); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs("deleteProfile"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result").getString("_id")); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs("deleteProfile"), data, options); - } - - return this; - } - - /** - * {@link #deleteProfile(String, Options, ResponseListener)} - */ - public Security deleteProfile(final String id, final ResponseListener listener) throws JSONException { - return deleteProfile(id, null, listener); - } - - /** - * {@link #deleteProfile(String, Options, ResponseListener)} - */ - public Security deleteProfile(final String id, final Options options) throws JSONException { - return deleteProfile(id, options, null); - } - - /** - * {@link #deleteProfile(String, Options, ResponseListener)} - */ - public Security deleteProfile(final String id) throws JSONException { - return deleteProfile(id, null, null); - } - - /** - * Returns the next batch of searched profiles with scroll - * - * @param scroll Scroll object obtained doing a scroll search - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void scrollProfiles(final Scroll scroll, final Options options, final ResponseListener listener) throws JSONException { - JSONObject request; - - try { - request = new JSONObject().put("body", new JSONObject()); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - - if (listener == null) { - throw new IllegalArgumentException("listener cannot be null"); - } - - if (scroll.getScrollId() == null) { - throw new IllegalArgumentException("Security.scrollProfiles: scrollId is required"); - } - - options.setScrollId(scroll.getScrollId()); - - try { - this.kuzzle.query(buildQueryArgs("scrollProfiles"), request, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - try { - JSONArray hits = object.getJSONObject("result").getJSONArray("hits"); - ArrayList profiles = new ArrayList<>(); - - for (int i = 0; i < hits.length(); i++) { - JSONObject hit = hits.getJSONObject(i); - Profile profile = new Profile(Security.this.kuzzle, hit.getString("_id"), hit.getJSONObject("_source"), hit.getJSONObject("_meta")); - - profiles.add(profile); - } - - SecurityDocumentList response = new SecurityDocumentList(profiles, hits.length(), scroll); - - listener.onSuccess(response); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #scrollProfiles(Scroll, Options, ResponseListener)} - */ - public void scrollProfiles(Scroll scroll, final ResponseListener listener) throws JSONException { - this.scrollProfiles(scroll, new Options(), listener); - } - - /** - * Update a profile's content - * - * @param id ID of the profile to update - * @param policies List of policies to apply to this profile - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Security updateProfile(final String id, final JSONObject[] policies, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.updateProfile: cannot update a profile with ID null"); - } - - JSONObject data = new JSONObject().put("_id", id); - data.put("body", new JSONObject().put("policies", new JSONArray(Arrays.asList(policies)))); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs("updateProfile"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(new Profile(Security.this.kuzzle, response.getJSONObject("result").getString("_id"), response.getJSONObject("result").getJSONObject("_source"), response.getJSONObject("result").getJSONObject("_meta"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs("updateProfile"), data, options); - } - - return this; - } - - /** - * {@link #updateProfile(String, JSONObject[], Options, ResponseListener)} - */ - public Security updateProfile(final String id, final JSONObject[] policies, final Options options) throws JSONException { - return updateProfile(id, policies, options, null); - } - - /** - * {@link #updateProfile(String, JSONObject[], Options, ResponseListener)} - */ - public Security updateProfile(final String id, final JSONObject[] policies, final ResponseListener listener) throws JSONException { - return this.updateProfile(id, policies, null, listener); - } - - /** - * {@link #updateProfile(String, JSONObject[], Options, ResponseListener)} - */ - public Security updateProfile(final String id, final JSONObject[] policies) throws JSONException { - return updateProfile(id, policies, null, null); - } - - /** - * Instantiate a new Profile object. - * Does not create it in Kuzzle. - * - * @param id Profile unique identifier - * @param content Profile content - * @param meta Profile metadata - * @return new Profile object - * @throws JSONException - */ - public Profile profile(final String id, final JSONObject content, final JSONObject meta) throws JSONException { - return new Profile(this.kuzzle, id, content, meta); - } - - /** - * {@link #profile(String, JSONObject, JSONObject)} - */ - public Profile profile(final String id, final JSONObject content) throws JSONException { - return new Profile(this.kuzzle, id, content, null); - } - - /** - * {@link #profile(String, JSONObject, JSONObject)} - */ - public Profile profile(final String id) throws JSONException { - return new Profile(this.kuzzle, id, null, null); - } - - /** - * Get a specific user from kuzzle using its unique ID - * - * @param id User ID to retrieve - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void fetchUser(final String id, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.fetchUser: cannot get user with ID null"); - } - - if (listener == null) { - throw new IllegalArgumentException("Security.fetchUser: a callback listener is required"); - } - - JSONObject data = new JSONObject().put("_id", id); - - this.kuzzle.query(buildQueryArgs("getUser"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - listener.onSuccess(new User(Security.this.kuzzle, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - - /** - * {@link #fetchUser(String, Options, ResponseListener)} - */ - public void fetchUser(final String id, final ResponseListener listener) throws JSONException { - fetchUser(id, null, listener); - } - - /** - * Replaces an existing user in Kuzzle. - * The new content must contain a "profileIds" attribute, an array - * listing the attached profiles for this user - * - * @param id ID of the user to replace - * @param content New user content - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void replaceUser(final String id, final JSONObject content, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.replaceUser: cannot replace user without an ID"); - } - - String action = "replaceUser"; - - JSONObject data = new JSONObject().put("_id", id).put("body", content); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs(action), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - listener.onSuccess(new User(Security.this.kuzzle, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs(action), data, options); - } - } - - /** - * {@link #replaceUser(String, JSONObject, Options, ResponseListener)} - */ - public void replaceUser(final String id, final JSONObject content, final Options options) throws JSONException { - replaceUser(id, content, options, null); - } - - /** - * {@link #replaceUser(String, JSONObject, Options, ResponseListener)} - */ - public void replaceUser(final String id, final JSONObject content, final ResponseListener listener) throws JSONException { - replaceUser(id, content, null, listener); - } - - /** - * {@link #replaceUser(String, JSONObject, Options, ResponseListener)} - */ - public void replaceUser(final String id, final JSONObject content) throws JSONException { - replaceUser(id, content, null, null); - } - - /** - * Searches users using a set of filters - * - * @param filters Search filters - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void searchUsers(JSONObject filters, final Options options, final ResponseListener listener) throws JSONException { - - if (filters == null) { - throw new IllegalArgumentException("Security.searchUsers: cannot perform a search with null filters"); - } - - if (listener == null) { - throw new IllegalArgumentException("Security.searchUsers: a callback listener is required"); - } - - JSONObject data = new JSONObject().put("body", filters); - - this.kuzzle.query(buildQueryArgs("searchUsers"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - JSONArray documents = result.getJSONArray("hits"); - int documentsLength = documents.length(); - ArrayList users = new ArrayList<>(); - - for (int i = 0; i < documentsLength; i++) { - JSONObject document = documents.getJSONObject(i); - users.add(new User(Security.this.kuzzle, document.getString("_id"), document.getJSONObject("_source"), document.getJSONObject("_meta"))); - } - - Scroll scroll = new Scroll(); - - if (result.has("scrollId")) { - scroll.setScrollId(result.getString("scrollId")); - } - - listener.onSuccess(new SecurityDocumentList(users, result.getLong("total"), scroll)); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - - /** - * {@link #searchUsers(JSONObject, Options, ResponseListener)} - */ - public void searchUsers(JSONObject filters, final ResponseListener listener) throws JSONException { - searchUsers(filters, null, listener); - } - - /** - * Create a new user in Kuzzle. - * - * @param id ID of the user to create - * @param content User content - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void createUser(final String id, final JSONObject content, final Options options, final ResponseListener listener) throws JSONException { - String action = "createUser"; - if (id == null || content == null) { - throw new IllegalArgumentException("Security.createUser: cannot create a user with a null ID or content"); - } - - JSONObject data = new JSONObject().put("_id", id).put("body", content); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs(action), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - listener.onSuccess(new User(Security.this.kuzzle, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs(action), data, options); - } - } - - /** - * {@link #createUser(String, JSONObject, Options, ResponseListener)} - */ - public void createUser(final String id, final JSONObject content, final Options options) throws JSONException { - createUser(id, content, options, null); - } - - /** - * {@link #createUser(String, JSONObject, Options, ResponseListener)} - */ - public void createUser(final String id, final JSONObject content, final ResponseListener listener) throws JSONException { - createUser(id, content, null, listener); - } - - /** - * {@link #createUser(String, JSONObject, Options, ResponseListener)} - */ - public void createUser(final String id, final JSONObject content) throws JSONException { - createUser(id, content, null, null); - } - - /** - * Create a new restricted user in Kuzzle. - * - * This function will create a new user. It is not usable to update an existing user. - * This function allows anonymous users to create a "restricted" user with predefined rights. - * - * @param id ID of the user to create - * @param content New user content - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void createRestrictedUser(final String id, final JSONObject content, final Options options, final ResponseListener listener) throws JSONException { - if (id == null || content == null) { - throw new IllegalArgumentException("Security.createRestrictedUser: cannot create a user with a null ID or content"); - } - - if (content.has("profileIds")) { - throw new IllegalArgumentException("Security.createRestrictedUser: cannot provide profileIds"); - } - - JSONObject data = new JSONObject().put("_id", id).put("body", content); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs("createRestrictedUser"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONObject result = response.getJSONObject("result"); - listener.onSuccess(new User(Security.this.kuzzle, result.getString("_id"), result.getJSONObject("_source"), result.getJSONObject("_meta"))); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs("createRestrictedUser"), data, options); - } - } - - /** - * {@link #createRestrictedUser(String, JSONObject, Options, ResponseListener)} - */ - public void createRestrictedUser(final String id, final JSONObject content, final Options options) throws JSONException { - createRestrictedUser(id, content, options, null); - } - - /** - * {@link #createRestrictedUser(String, JSONObject, Options, ResponseListener)} - */ - public void createRestrictedUser(final String id, final JSONObject content, final ResponseListener listener) throws JSONException { - createRestrictedUser(id, content, null, listener); - } - - /** - * {@link #createRestrictedUser(String, JSONObject, Options, ResponseListener)} - */ - public void createRestrictedUser(final String id, final JSONObject content) throws JSONException { - createRestrictedUser(id, content, null, null); - } - - /** - * Delete a user from Kuzzle - * - * @param id ID of the user to delete - * @param options Request optional arguments - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Security deleteUser(final String id, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.deleteUser: cannot delete user with ID null"); - } - - JSONObject data = new JSONObject().put("_id", id); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs("deleteUser"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result").getString("_id")); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs("deleteUser"), data, options); - } - - return this; - } - - /** - * {@link #deleteUser(String, Options, ResponseListener)} - */ - public Security deleteUser(final String id, final Options options) throws JSONException { - return deleteUser(id, options, null); - } - - /** - * {@link #deleteUser(String, Options, ResponseListener)} - */ - public Security deleteUser(final String id, final ResponseListener listener) throws JSONException { - return deleteUser(id, null, listener); - } - - /** - * {@link #deleteUser(String, Options, ResponseListener)} - */ - public Security deleteUser(final String id) throws JSONException { - return deleteUser(id, null, null); - } - - /** - * Returns the next batch of searched users - * - * @param scroll Scroll object, obtained using a scroll search - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void scrollUsers(final Scroll scroll, final Options options, final ResponseListener listener) throws JSONException { - JSONObject request; - - try { - request = new JSONObject().put("body", new JSONObject()); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - - if (listener == null) { - throw new IllegalArgumentException("listener cannot be null"); - } - - if (scroll.getScrollId() == null) { - throw new IllegalArgumentException("Security.scrollUsers: scrollId is required"); - } - - options.setScrollId(scroll.getScrollId()); - - try { - this.kuzzle.query(buildQueryArgs("scrollUsers"), request, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject object) { - try { - JSONArray hits = object.getJSONObject("result").getJSONArray("hits"); - ArrayList users = new ArrayList<>(); - - for (int i = 0; i < hits.length(); i++) { - JSONObject hit = hits.getJSONObject(i); - User user = new User(Security.this.kuzzle, hit.getString("_id"), hit.getJSONObject("_source"), hit.getJSONObject("_meta")); - - users.add(user); - } - - SecurityDocumentList response = new SecurityDocumentList(users, hits.length(), scroll); - - listener.onSuccess(response); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #scrollUsers(Scroll, Options, ResponseListener)} - */ - public void scrollUsers(Scroll scroll, final ResponseListener listener) throws JSONException { - this.scrollUsers(scroll, new Options(), listener); - } - - /** - * Update a user. - * - * @param id ID of the user to update - * @param content User content to update - * @param options Request options - * @param listener Response callback listener - * @return this - * @throws JSONException - */ - public Security updateUser(final String id, final JSONObject content, final Options options, final ResponseListener listener) throws JSONException { - if (id == null) { - throw new IllegalArgumentException("Security.updateUser: cannot update user without an ID"); - } - - JSONObject data = new JSONObject().put("_id", id); - data.put("body", content); - - if (listener != null) { - this.kuzzle.query(buildQueryArgs("updateUser"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(new User(Security.this.kuzzle, response.getJSONObject("result").getString("_id"), response.getJSONObject("result").getJSONObject("_source"), response.getJSONObject("result").getJSONObject("_meta"))); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(buildQueryArgs("updateUser"), data, options); - } - - return this; - } - - /** - * {@link #updateUser(String, JSONObject, Options, ResponseListener)} - */ - public Security updateUser(final String id, final JSONObject content, final ResponseListener listener) throws JSONException { - return updateUser(id, content, null, listener); - } - - /** - * {@link #updateUser(String, JSONObject, Options, ResponseListener)} - */ - public Security updateUser(final String id, final JSONObject content, final Options options) throws JSONException { - return updateUser(id, content, options, null); - } - - /** - * {@link #updateUser(String, JSONObject, Options, ResponseListener)} - */ - public Security updateUser(final String id, final JSONObject content) throws JSONException { - return updateUser(id, content, null, null); - } - - /** - * Instantiate a new User object - * Does not create it in Kuzzle - * - * @param id User unique identifier - * @param content User content - * @param meta User metadata - * @return new User object - * @throws JSONException - */ - public User user(final String id, final JSONObject content, final JSONObject meta) throws JSONException { - return new User(this.kuzzle, id, content, meta); - } - - /** - * {@link #user(String, JSONObject, JSONObject)} - */ - public User user(final String id, final JSONObject content) throws JSONException { - return new User(this.kuzzle, id, content, null); - } - - /** - * {@link #user(String, JSONObject, JSONObject)} - */ - public User user(final String id) throws JSONException { - return new User(this.kuzzle, id, null, null); - } - - /** - * {@link #isActionAllowed(JSONObject[], String, String, String, String)} - */ - public Policies isActionAllowed(final JSONObject[] policies, final String controller, final String action) { - return this.isActionAllowed(policies, controller, action, null, null); - } - - /** - * {@link #isActionAllowed(JSONObject[], String, String, String, String)} - */ - public Policies isActionAllowed(final JSONObject[] policies, final String controller, final String action, final String index) { - return this.isActionAllowed(policies, controller, action, index, null); - } - - /** - * Tells whether an action is allowed, denied or conditional based on the rights - * policies provided as the first argument. An action is defined as a couple of - * action and controller (required), plus a data index and a collection (optional). - * - * @param policies List of policies containing the current authorizations - * @param controller Kuzzle API Controller - * @param action Controller action - * @param index Data index - * @param collection Data collection - * @return action authorization status - */ - public Policies isActionAllowed(final JSONObject[] policies, final String controller, final String action, final String index, final String collection) { - if (policies == null) { - throw new IllegalArgumentException("Security.isActionAllowed: policies are mandatory."); - } - if (controller == null || controller.isEmpty()) { - throw new IllegalArgumentException("Security.isActionAllowed: controller is mandatory."); - } - if (action == null || action.isEmpty()) { - throw new IllegalArgumentException("Security.isActionAllowed: action is mandatory."); - } - - JSONObject[] filteredPolicies; - try { - filteredPolicies = filterPolicy(policies, "controller", controller); - filteredPolicies = filterPolicy(filteredPolicies, "action", action); - filteredPolicies = filterPolicy(filteredPolicies, "index", index); - filteredPolicies = filterPolicy(filteredPolicies, "collection", collection); - - for (JSONObject filteredPolicy : filteredPolicies) { - if (filteredPolicy.getString("value").equals(Policies.allowed.toString())) { - return Policies.allowed; - } - } - - for (JSONObject filteredPolicy : filteredPolicies) { - if (filteredPolicy.getString("value").equals(Policies.conditional.toString())) { - return Policies.conditional; - } - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return Policies.denied; - } - - private JSONObject[] filterPolicy(final JSONObject[] policies, final String attr, final String attrInput) throws JSONException { - ArrayList filteredPolicies = new ArrayList<>(); - - for (JSONObject policy : policies) { - String attrObject = policy.getString(attr); - if (attrObject.equals(attrInput) || attrObject.equals("*")) { - filteredPolicies.add(policy); - } - } - return filteredPolicies.toArray(new JSONObject[0]); - } - - /** - * {@link #getUserRights(String, Options, ResponseListener)} - */ - public Security getUserRights(final String id, final ResponseListener listener) { - return getUserRights(id, null, listener); - } - - /** - * Gets the rights array of a given user. - * - * @param id User ID to retrieve the rights from - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Security getUserRights(final String id, final Options options, final ResponseListener listener) { - if (id == null || id.isEmpty()) { - throw new IllegalArgumentException("Security.getUserRights: id is mandatory."); - } - if (listener == null) { - throw new IllegalArgumentException("Security.getUserRights: listener is mandatory."); - } - try { - JSONObject data = new JSONObject() - .put("_id", id); - kuzzle.query(buildQueryArgs("getUserRights"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONArray arr = response.getJSONObject("result").getJSONArray("hits"); - JSONObject[] rights = new JSONObject[arr.length()]; - - for (int i = 0; i < arr.length(); i++) { - rights[i] = arr.getJSONObject(i); - } - listener.onSuccess(rights); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - /** - * {@link #createCredentials(String, String, JSONObject, Options, ResponseListener)} - */ - public Security createCredentials(final String strategy, final String kuid, final JSONObject credentials) { - return createCredentials(strategy, kuid, credentials, null, null); - } - - /** - * {@link #createCredentials(String, String, JSONObject, Options, ResponseListener)} - */ - public Security createCredentials(final String strategy, final String kuid, final JSONObject credentials, final Options options) { - return createCredentials(strategy, kuid, credentials, options, null); - } - - /** - * {@link #createCredentials(String, String, JSONObject, Options, ResponseListener)} - */ - public Security createCredentials(final String strategy, final String kuid, final JSONObject credentials, final ResponseListener listener) { - return createCredentials(strategy, kuid, credentials, null, listener); - } - - /** - * Create credentials of the specified strategy for the provided user. - * - * @param strategy Strategy name to add to the user - * @param kuid Kuzzle User unique Identifier for the user to update - * @param credentials Credentials content - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Security createCredentials(final String strategy, final String kuid, final JSONObject credentials, final Options options, final ResponseListener listener) { - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("_id", kuid) - .put("body", credentials); - kuzzle.query(buildQueryArgs("security", "createCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (listener != null) { - listener.onSuccess(response.getJSONObject("result")); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #deleteCredentials(String, String, Options, ResponseListener)} - */ - public Security deleteCredentials(final String strategy, final String kuid) { - return deleteCredentials(strategy, kuid, null, null); - } - - /** - * {@link #deleteCredentials(String, String, Options, ResponseListener)} - */ - public Security deleteCredentials(final String strategy, final String kuid, final Options options) { - return deleteCredentials(strategy, kuid, options, null); - } - - /** - * {@link #deleteCredentials(String, String, Options, ResponseListener)} - */ - public Security deleteCredentials(final String strategy, final String kuid, final ResponseListener listener) { - return deleteCredentials(strategy, kuid, null, listener); - } - - /** - * Delete credentials of the specified strategy for the user kuid . - * - * @param strategy Strategy name to delete from the user - * @param kuid Kuzzle User unique Identifier for the user to update - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Security deleteCredentials(final String strategy, final String kuid, final Options options, final ResponseListener listener) { - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("_id", kuid); - kuzzle.query(buildQueryArgs("security", "deleteCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (listener != null) { - listener.onSuccess(response.getJSONObject("result")); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #getAllCredentialFields(Options, ResponseListener)} - */ - public void getAllCredentialFields(final ResponseListener listener) { - getAllCredentialFields(null, listener); - } - - /** - * Gets a list of all accepted fields per authentication strategy. - * - * @param options - Request options - * @param listener - Response callback listener - */ - public void getAllCredentialFields(final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Security.getAllCredentialFields: listener is mandatory."); - } - try { - JSONObject body = new JSONObject(); - kuzzle.query(buildQueryArgs("security", "getAllCredentialFields"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #getCredentialFields(String, Options, ResponseListener)} - */ - public void getCredentialFields(final String strategy, final ResponseListener listener) { - getCredentialFields(strategy, null, listener); - } - - /** - * Retrieve the list of accepted field names by the specified strategy. - * - * @param strategy Name of the strategy to get - * @param options Request options - * @param listener Response callback listener - */ - public void getCredentialFields(final String strategy, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Security.getAllCredentialFields: listener is mandatory."); - } - try { - JSONObject body = new JSONObject() - .put("strategy", strategy); - kuzzle.query(buildQueryArgs("security", "getCredentialFields"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONArray array = response.getJSONObject("result").getJSONArray("hits"); - int length = array.length(); - String[] fields = new String[length]; - for (int i = 0; i < length; i++) { - fields[i] = array.getString(i); - } - listener.onSuccess(fields); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #getCredentials(String, String, Options, ResponseListener)} - */ - public void getCredentials(final String strategy, final String kuid, final ResponseListener listener) { - getCredentials(strategy, kuid, null, listener); - } - - /** - * Get credential information of the specified strategy for the user kuid. - * - * @param strategy Strategy name to get - * @param kuid User unique identifier - * @param options Request options - * @param listener Response callback listener - */ - public void getCredentials(final String strategy, final String kuid, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Security.getCredentials: listener is mandatory."); - } - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("_id", kuid); - kuzzle.query(buildQueryArgs("security", "getCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getJSONObject("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #hasCredentials(String, String, Options, ResponseListener)} - */ - public void hasCredentials(final String strategy, final String kuid, final ResponseListener listener) { - hasCredentials(strategy, kuid, null, listener); - } - - /** - * Check the existence of the specified strategy’s credentials for the user kuid. - * - * @param strategy Strategy name to check - * @param kuid User unique identifier - * @param options Request options - * @param listener Response callback listener - */ - public void hasCredentials(final String strategy, final String kuid, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Security.hasCredentials: listener is mandatory."); - } - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("_id", kuid); - kuzzle.query(buildQueryArgs("security", "hasCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getBoolean("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - /** - * {@link #updateCredentials(String, String, JSONObject, Options, ResponseListener)} - */ - public Security updateCredentials(final String strategy, final String kuid, final JSONObject credentials) { - return updateCredentials(strategy, kuid, credentials, null, null); - } - - /** - * {@link #updateCredentials(String, String, JSONObject, Options, ResponseListener)} - */ - public Security updateCredentials(final String strategy, final String kuid, final JSONObject credentials, final Options options) { - return updateCredentials(strategy, kuid, credentials, options, null); - } - - /** - * {@link #updateCredentials(String, String, JSONObject, Options, ResponseListener)} - */ - public Security updateCredentials(final String strategy, final String kuid, final JSONObject credentials, final ResponseListener listener) { - return updateCredentials(strategy, kuid, credentials, null, listener); - } - - /** - * Updates credentials of the specified strategy for the user kuid. - * - * @param strategy Strategy name to update - * @param kuid User unique identifier - * @param credentials Credentials content to update - * @param options Request options - * @param listener Response callback listener - * @return this - */ - public Security updateCredentials(final String strategy, final String kuid, final JSONObject credentials, final Options options, final ResponseListener listener) { - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("_id", kuid) - .put("body", credentials); - kuzzle.query(buildQueryArgs("security", "updateCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - if (listener != null) { - listener.onSuccess(response.getJSONObject("result")); - } - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - if (listener != null) { - listener.onError(error); - } - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - - return this; - } - - /** - * {@link #validateCredentials(String, String, JSONObject, Options, ResponseListener)} - */ - public void validateCredentials(final String strategy, final String kuid, final JSONObject credentials, final ResponseListener listener) { - validateCredentials(strategy, kuid, credentials, null, listener); - } - - /** - * Validate credentials of the specified strategy for the user kuid. - * - * @param strategy Strategy name to validate - * @param kuid User unique identifier - * @param options Request options - * @param listener Response callback listener - */ - public void validateCredentials(final String strategy, final String kuid, final JSONObject credentials, final Options options, final ResponseListener listener) { - if (listener == null) { - throw new IllegalArgumentException("Security.getCredentials: listener is mandatory."); - } - try { - JSONObject body = new JSONObject() - .put("strategy", strategy) - .put("credentials", credentials) - .put("_id", kuid); - kuzzle.query(buildQueryArgs("security", "validateCredentials"), body, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - try { - listener.onSuccess(response.getBoolean("result")); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - -} diff --git a/src/main/java/io/kuzzle/sdk/security/User.java b/src/main/java/io/kuzzle/sdk/security/User.java deleted file mode 100644 index 568f8670..00000000 --- a/src/main/java/io/kuzzle/sdk/security/User.java +++ /dev/null @@ -1,360 +0,0 @@ -package io.kuzzle.sdk.security; - - - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.Arrays; -import java.util.ArrayList; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.security.Profile; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -/** - * This class handles users management in Kuzzle - */ -public class User extends AbstractSecurityDocument { - private ArrayList profileIds = new ArrayList<>(); - - private JSONObject credentials = new JSONObject(); - - /** - * Instantiates a new Kuzzle user. - * - * @param kuzzle Kuzzle instance to attach - * @param id User unique identifier - * @param content User content - * @param meta User metadata - * @throws JSONException - */ - public User(final Kuzzle kuzzle, final String id, final JSONObject content, final JSONObject meta) throws JSONException { - super(kuzzle, id, null, meta); - this.deleteActionName = "deleteUser"; - this.updateActionName = "updateUser"; - - if (content != null) { - this.content = new JSONObject(content.toString()); - - if (content.has("profileIds")) { - JSONArray profiles = content.getJSONArray("profileIds"); - - for (int i = 0; i < profiles.length(); i++) { - this.profileIds.add(profiles.getString(i)); - } - } - } - } - - /** - * Set a new profiles set for this user - * - * @param profileIds Array of profile identifiers - * @return this - */ - public User setProfiles(final String[] profileIds) { - if (profileIds == null) { - throw new IllegalArgumentException("User.setProfiles: you must provide an array of profiles IDs strings"); - } - - this.profileIds.clear(); - this.profileIds.addAll(Arrays.asList(profileIds)); - - return this; - } - - /** - * Adds a new profile to the profiles set of this user - * - * @param profile Profile unique ID to add - * @return this - */ - public User addProfile(final String profile) { - if (profile == null) { - throw new IllegalArgumentException("User.addProfile: you must provide a string"); - } - - this.profileIds.add(profile); - - return this; - } - - /** - * Replace a user in Kuzzle with this object's content - * - * @param options Request optional arguments - * @param listener -Callback listener - * @return this - * @throws JSONException - */ - public User replace(final Options options, final ResponseListener listener) throws JSONException { - JSONObject data = this.serialize(); - - if (listener != null) { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("replaceUser"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - listener.onSuccess(User.this); - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("replaceUser"), data, options); - } - - return this; - } - - /** - * {@link #replace(Options, ResponseListener)} - */ - public User replace(final ResponseListener listener) throws JSONException { - return replace(null, listener); - } - - /** - * {@link #replace(Options, ResponseListener)} - */ - public User replace(final Options options) throws JSONException { - return replace(options, null); - } - - /** - * {@link #replace(Options, ResponseListener)} - */ - public User replace() throws JSONException { - return replace(null, null); - } - - /** - * Create this user into Kuzzle. - * - * @param options Request optional arguments - * @param listener Callback listener - * @return this - * @throws JSONException - */ - public User create(final Options options, final ResponseListener listener) throws JSONException { - JSONObject data = this.creationSerialize(); - - if (listener != null) { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createUser"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - listener.onSuccess(User.this); - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createUser"), data, options); - } - - return this; - } - - /** - * {@link #create(Options, ResponseListener)} - */ - public User create(final ResponseListener listener) throws JSONException { - return create(null, listener); - } - - /** - * {@link #create(Options, ResponseListener)} - */ - public User create(final Options options) throws JSONException { - return create(options, null); - } - - /** - * {@link #create(Options, ResponseListener)} - */ - public User create() throws JSONException { - return create(null, null); - } - - /** - * Saves this object's content as a restricted user into Kuzzle. - * - * @param options Request optional arguments - * @param listener Callback listener - * @return this - * @throws JSONException - */ - public User saveRestricted(final Options options, final ResponseListener listener) throws JSONException { - JSONObject data = this.serialize(); - - if (listener != null) { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createRestrictedUser"), data, options, new OnQueryDoneListener() { - @Override - public void onSuccess(JSONObject response) { - listener.onSuccess(User.this); - } - - @Override - public void onError(JSONObject error) { - listener.onError(error); - } - }); - } - else { - this.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createRestrictedUser"), data, options); - } - - return this; - } - - /** - * {@link #saveRestricted(Options, ResponseListener)} - */ - public User saveRestricted(final ResponseListener listener) throws JSONException { - return saveRestricted(null, listener); - } - - /** - * {@link #saveRestricted(Options, ResponseListener)} - */ - public User saveRestricted(final Options options) throws JSONException { - return saveRestricted(options, null); - } - - /** - * {@link #saveRestricted(Options, ResponseListener)} - */ - public User saveRestricted() throws JSONException { - return saveRestricted(null, null); - } - - /** - * Return a JSONObject representing a serialized version of this object - * - * @return serialized version of this object - * @throws JSONException - */ - public JSONObject serialize() throws JSONException { - JSONObject - data = new JSONObject().put("_id", this.id), - content = new JSONObject(this.content.toString()); - - if (this.profileIds.size() > 0) { - content.put("profileIds", new JSONArray(this.profileIds)); - } - - data.put("body", content); - - return data; - } - - /** - * Return a JSONObject representing a serialized version of this object - * - * @return serialized version of this object - * @throws JSONException - */ - public JSONObject creationSerialize() throws JSONException { - JSONObject - data = new JSONObject().put("_id", this.id), - body = new JSONObject(), - content = new JSONObject(this.content.toString()), - credentials = new JSONObject(this.credentials.toString()); - - if (this.profileIds.size() > 0) { - content.put("profileIds", new JSONArray(this.profileIds)); - } - - body.put("content", content); - body.put("credentials", credentials); - data.put("body", body); - - return data; - } - - /** - * @return the associated profile identifiers - */ - public String[] getProfileIds() { - return this.profileIds.toArray(new String[0]); - } - - /** - * {@link #getProfiles(Options, ResponseListener)} - */ - public void getProfiles(final ResponseListener listener) throws JSONException { - getProfiles(null, listener); - } - - /** - * Gets the profile objects from the associated profile identifiers - * - * @param options Request optional arguments - * @param listener Response callback listener - * @throws JSONException - */ - public void getProfiles(final Options options, final ResponseListener listener) throws JSONException { - if (listener == null) { - throw new IllegalArgumentException("User.getProfiles: a valid ResponseListener object is required"); - } - - final Profile[] profiles = new Profile[this.profileIds.size()]; - - if (this.profileIds.size() == 0) { - listener.onSuccess(profiles); - return; - } - - // using an array to allow these variables to be final - // while keeping the possibility to change their value - final int[] fetched = {0}; - final boolean[] errored = {false}; - - for (int i = 0; i < this.profileIds.size(); i++) { - this.kuzzleSecurity.fetchProfile(this.profileIds.get(i), options, new ResponseListener() { - @Override - public void onSuccess(Profile response) { - profiles[fetched[0]] = response; - fetched[0]++; - - if (fetched[0] == User.this.profileIds.size()) { - listener.onSuccess(profiles); - } - } - - @Override - public void onError(JSONObject error) { - // prevents triggering the listener multiple times - if (errored[0]) { - return; - } - - errored[0] = true; - listener.onError(error); - } - }); - } - } - - /** - * User credentials setter - * @param credentials New credentials value - * @return this - */ - public User setCredentials(JSONObject credentials) { - this.credentials = credentials; - - return this; - } -} diff --git a/src/main/java/io/kuzzle/sdk/state/KuzzleQueue.java b/src/main/java/io/kuzzle/sdk/state/KuzzleQueue.java deleted file mode 100644 index f0b7c499..00000000 --- a/src/main/java/io/kuzzle/sdk/state/KuzzleQueue.java +++ /dev/null @@ -1,61 +0,0 @@ -package io.kuzzle.sdk.state; - -import java.util.ArrayDeque; -import java.util.Iterator; -import java.util.Queue; - -/** - * The type KuzzleQueue. - * - * @param the type parameter - */ -public class KuzzleQueue implements Iterable { - - private Queue _queue = new ArrayDeque<>(); - - /** - * Add to queue. - * - * @param object Item to queue - */ - public synchronized void addToQueue(T object) { - _queue.add(object); - } - - /** - * Dequeue t. - * - * @return Dequeued item - */ - public synchronized T dequeue() { - return _queue.poll(); - } - - private States _currentState = States.DISCONNECTED; - - /** - * @param states New connection state value - */ - public void setState(States states) { - _currentState = states; - } - - /** - * @return Connection state value - */ - public States state() { - return _currentState; - } - - /** - * @return queue content - */ - public Queue getQueue() { - return _queue; - } - - @Override - public Iterator iterator() { - return _queue.iterator(); - } -} diff --git a/src/main/java/io/kuzzle/sdk/state/States.java b/src/main/java/io/kuzzle/sdk/state/States.java deleted file mode 100644 index 5c152558..00000000 --- a/src/main/java/io/kuzzle/sdk/state/States.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.kuzzle.sdk.state; - -/** - * The enum States. - */ -public enum States { - CONNECTING, - DISCONNECTED, - CONNECTED, - INITIALIZING, - READY, - LOGGED_OUT, - ERROR, - OFFLINE -} diff --git a/src/main/java/io/kuzzle/sdk/util/Event.java b/src/main/java/io/kuzzle/sdk/util/Event.java deleted file mode 100644 index 4854195b..00000000 --- a/src/main/java/io/kuzzle/sdk/util/Event.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.kuzzle.sdk.util; - -import io.kuzzle.sdk.listeners.EventListener; - -public abstract class Event implements EventListener { - private io.kuzzle.sdk.enums.Event type; - - /** - * Instantiates a new Event. - * - * @param type Event type - */ - public Event(io.kuzzle.sdk.enums.Event type) { - this.type = type; - } - - public abstract void trigger(Object... args); - - /** - * @return Event type value - */ - public io.kuzzle.sdk.enums.Event getType() { - return this.type; - } -} diff --git a/src/main/java/io/kuzzle/sdk/util/EventList.java b/src/main/java/io/kuzzle/sdk/util/EventList.java deleted file mode 100644 index 8b7ec217..00000000 --- a/src/main/java/io/kuzzle/sdk/util/EventList.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.kuzzle.sdk.util; - -import java.util.HashMap; -import io.kuzzle.sdk.listeners.EventListener; - -public class EventList extends HashMap { - public long lastEmitted = 0; -} diff --git a/src/main/java/io/kuzzle/sdk/util/KuzzleJSONObject.java b/src/main/java/io/kuzzle/sdk/util/KuzzleJSONObject.java deleted file mode 100644 index 32e5d87b..00000000 --- a/src/main/java/io/kuzzle/sdk/util/KuzzleJSONObject.java +++ /dev/null @@ -1,58 +0,0 @@ -package io.kuzzle.sdk.util; - -import org.json.JSONException; -import org.json.JSONObject; - -public class KuzzleJSONObject extends JSONObject { - - @Override - public KuzzleJSONObject put(final String name, final Object value) { - try { - super.put(name, value); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - @Override - public KuzzleJSONObject put(final String name, final long value) { - try { - super.put(name, value); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - @Override - public KuzzleJSONObject put(final String name, final int value) { - try { - super.put(name, value); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - @Override - public KuzzleJSONObject put(final String name, final double value) { - try { - super.put(name, value); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - - @Override - public KuzzleJSONObject put(final String name, final boolean value) { - try { - super.put(name, value); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return this; - } - -} diff --git a/src/main/java/io/kuzzle/sdk/util/OfflineQueueLoader.java b/src/main/java/io/kuzzle/sdk/util/OfflineQueueLoader.java deleted file mode 100644 index f2267740..00000000 --- a/src/main/java/io/kuzzle/sdk/util/OfflineQueueLoader.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.kuzzle.sdk.util; - -import io.kuzzle.sdk.state.KuzzleQueue; - -public interface OfflineQueueLoader { - KuzzleQueue load(); -} diff --git a/src/main/java/io/kuzzle/sdk/util/QueryObject.java b/src/main/java/io/kuzzle/sdk/util/QueryObject.java deleted file mode 100644 index 1abc119f..00000000 --- a/src/main/java/io/kuzzle/sdk/util/QueryObject.java +++ /dev/null @@ -1,86 +0,0 @@ -package io.kuzzle.sdk.util; - -import org.json.JSONObject; - -import java.util.Date; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -public class QueryObject { - private JSONObject query; - private String action; - private Options options; - private OnQueryDoneListener cb; - private Date timestamp; - - /** - * @return Callback to invoke with the query result - */ - public OnQueryDoneListener getCb() { - return cb; - } - - /** - * @param cb Callback to invoke with the query result - */ - public void setCb(OnQueryDoneListener cb) { - this.cb = cb; - } - - /** - * @return Controller action name to execute - */ - public String getAction() { - return action; - } - - /** - * @param action Controller action name to execute - */ - public void setAction(String action) { - this.action = action; - } - - /** - * @return Query options - */ - public Options getOptions() { - return options; - } - - /** - * @param options Query options - */ - public void setOptions(Options options) { - this.options = options; - } - - /** - * @return Query timestamp (Epoch time) - */ - public Date getTimestamp() { - return timestamp; - } - - /** - * @param timestamp Query timestamp (Epoch time) - */ - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - /** - * @return Query content - */ - public JSONObject getQuery() { - return query; - } - - /** - * @param query Query content - */ - public void setQuery(JSONObject query) { - this.query = query; - } -} diff --git a/src/main/java/io/kuzzle/sdk/util/QueueFilter.java b/src/main/java/io/kuzzle/sdk/util/QueueFilter.java deleted file mode 100644 index 8d7ad00b..00000000 --- a/src/main/java/io/kuzzle/sdk/util/QueueFilter.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.kuzzle.sdk.util; - -import org.json.JSONObject; - -public interface QueueFilter { - boolean filter(JSONObject object); -} diff --git a/src/main/java/io/kuzzle/sdk/util/Scroll.java b/src/main/java/io/kuzzle/sdk/util/Scroll.java deleted file mode 100644 index 36f217b5..00000000 --- a/src/main/java/io/kuzzle/sdk/util/Scroll.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.kuzzle.sdk.util; - - -public class Scroll { - private String scrollId; - - public void setScrollId(String scrollId) { - this.scrollId = scrollId; - } - - public boolean hasScrollId() { return !(scrollId == null); } - - public String getScrollId() { return scrollId; } -} diff --git a/src/test/java/io/kuzzle/test/API/Controllers/AuthControllerTest.java b/src/test/java/io/kuzzle/test/API/Controllers/AuthControllerTest.java new file mode 100644 index 00000000..92510a1c --- /dev/null +++ b/src/test/java/io/kuzzle/test/API/Controllers/AuthControllerTest.java @@ -0,0 +1,313 @@ +package io.kuzzle.test.API.Controllers; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.WebSocket; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +public class AuthControllerTest { + private AbstractProtocol networkProtocol = Mockito.mock(WebSocket.class); + + @Test + public void checkTokenTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().checkToken("my-token"); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "checkToken"); + assertEquals("my-token", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("token").toString()); + } + + @Test + public void createMyCredentialsTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ConcurrentHashMap credentials = new ConcurrentHashMap<>(); + credentials.put("username", "foo"); + credentials.put("password", "foobar"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().createMyCredentials("local", credentials); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "createMyCredentials"); + assertEquals(((KuzzleMap) arg.getValue()).getString("strategy"), "local"); + assertEquals("foo", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("username")); + assertEquals("foobar", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("password")); + } + + @Test + public void credentialsExistTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().credentialsExist("local"); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "credentialsExist"); + assertEquals("local", ((((KuzzleMap) arg.getValue()).getString("strategy")))); + } + + @Test + public void getMyCredentialsTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().getMyCredentials("local"); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "getMyCredentials"); + assertEquals("local", ((((KuzzleMap) arg.getValue()).getString("strategy")))); + } + + @Test + public void getMyRightsTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().getMyRights(); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "getMyRights"); + } + + @Test + public void getStrategies() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().getStrategies(); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "getStrategies"); + } + + @Test + public void loginSuccessTest() throws NotConnectedException, InternalException, InterruptedException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + CompletableFuture future = new CompletableFuture<>(); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + Response response = new Response(); + ConcurrentHashMap result = new ConcurrentHashMap<>(); + + result.put("jwt", "my-token"); + result.put("_id", "my-id"); + response.result = result; + + doReturn(future).when(kuzzleSpy).query(any(KuzzleMap.class)); + + ConcurrentHashMap credentials = new ConcurrentHashMap<>(); + credentials.put("username", "foo"); + credentials.put("password", "foobar"); + + kuzzleSpy.getAuthController().login("local", credentials); + future.complete(response); + Thread.sleep(1000); + verify(kuzzleSpy).setAuthenticationToken(eq("my-token")); + verify(kuzzleSpy).trigger(eq(Event.loginAttempt), eq(true)); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "login"); + assertEquals(((KuzzleMap) arg.getValue()).getString("strategy"), "local"); + assertEquals(((KuzzleMap) arg.getValue()).getString("expiresIn"), null); + assertEquals("foo", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("username")); + assertEquals("foobar", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("password")); + } + + @Test + public void loginSuccessWithExpiresInTest() throws NotConnectedException, InternalException, InterruptedException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + CompletableFuture future = new CompletableFuture<>(); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + Response response = new Response(); + ConcurrentHashMap result = new ConcurrentHashMap<>(); + + result.put("jwt", "my-token"); + result.put("_id", "my-id"); + response.result = result; + + doReturn(future).when(kuzzleSpy).query(any(KuzzleMap.class)); + + ConcurrentHashMap credentials = new ConcurrentHashMap<>(); + credentials.put("username", "foo"); + credentials.put("password", "foobar"); + + kuzzleSpy.getAuthController().login("local", credentials, "42h"); + future.complete(response); + Thread.sleep(1000); + verify(kuzzleSpy).setAuthenticationToken(eq("my-token")); + verify(kuzzleSpy).trigger(eq(Event.loginAttempt), eq(true)); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "login"); + assertEquals(((KuzzleMap) arg.getValue()).getString("strategy"), "local"); + assertEquals(((KuzzleMap) arg.getValue()).getString("expiresIn"), "42h"); + assertEquals("foo", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("username")); + assertEquals("foobar", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("password")); + } + + @Test + public void loginFailTest() throws NotConnectedException, InternalException, InterruptedException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + CompletableFuture future = new CompletableFuture<>(); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + Response response = new Response(); + response.result = new ConcurrentHashMap<>(); + + doReturn(future).when(kuzzleSpy).query(any(KuzzleMap.class)); + + ConcurrentHashMap credentials = new ConcurrentHashMap<>(); + credentials.put("username", "foo"); + credentials.put("password", "foobar"); + + kuzzleSpy.getAuthController().login("local", credentials); + future.complete(response); + Thread.sleep(1000); + verify(kuzzleSpy).setAuthenticationToken(eq(null)); + verify(kuzzleSpy).trigger(eq(Event.loginAttempt), eq(false)); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "login"); + assertEquals(((KuzzleMap) arg.getValue()).getString("strategy"), "local"); + assertEquals(((KuzzleMap) arg.getValue()).getString("expiresIn"), null); + assertEquals("foo", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("username")); + assertEquals("foobar", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("password")); + } + + @Test + public void refreshTokenTest() throws NotConnectedException, InternalException, InterruptedException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + CompletableFuture future = new CompletableFuture<>(); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + Response response = new Response(); + ConcurrentHashMap result = new ConcurrentHashMap<>(); + + result.put("jwt", "my-token"); + response.result = result; + + doReturn(future).when(kuzzleSpy).query(any(KuzzleMap.class)); + + kuzzleSpy.getAuthController().refreshToken(); + future.complete(response); + Thread.sleep(1000); + verify(kuzzleSpy).setAuthenticationToken(eq("my-token")); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "refreshToken"); + assertEquals(((KuzzleMap) arg.getValue()).getString("expiresIn"), null); + } + + @Test + public void refreshTokenWithExpiresInTest() throws NotConnectedException, InternalException, InterruptedException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + CompletableFuture future = new CompletableFuture<>(); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + Response response = new Response(); + ConcurrentHashMap result = new ConcurrentHashMap<>(); + + result.put("jwt", "my-token"); + response.result = result; + + doReturn(future).when(kuzzleSpy).query(any(KuzzleMap.class)); + + kuzzleSpy.getAuthController().refreshToken("42h"); + future.complete(response); + Thread.sleep(1000); + verify(kuzzleSpy).setAuthenticationToken(eq("my-token")); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "refreshToken"); + assertEquals(((KuzzleMap) arg.getValue()).getString("expiresIn"), "42h"); + } + + @Test + public void updateMyCredentialsTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ConcurrentHashMap credentials = new ConcurrentHashMap<>(); + credentials.put("username", "foo"); + credentials.put("password", "foobar"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().updateMyCredentials("local", credentials); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "updateMyCredentials"); + assertEquals(((KuzzleMap) arg.getValue()).getString("strategy"), "local"); + assertEquals("foo", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("username")); + assertEquals("foobar", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("password")); + } + + @Test + public void updateSelfTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ConcurrentHashMap credentials = new ConcurrentHashMap<>(); + credentials.put("username", "foo"); + credentials.put("password", "foobar"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().updateSelf(credentials); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "updateSelf"); + assertEquals("foo", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("username")); + assertEquals("foobar", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("password")); + } + + @Test + public void validateMyCredentialsTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ConcurrentHashMap credentials = new ConcurrentHashMap<>(); + credentials.put("username", "foo"); + credentials.put("password", "foobar"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getAuthController().validateMyCredentials("local", credentials); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "auth"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "validateMyCredentials"); + assertEquals(((KuzzleMap) arg.getValue()).getString("strategy"), "local"); + assertEquals("foo", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("username")); + assertEquals("foobar", ((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("password")); + } +} diff --git a/src/test/java/io/kuzzle/test/API/Controllers/CollectionTest.java b/src/test/java/io/kuzzle/test/API/Controllers/CollectionTest.java new file mode 100644 index 00000000..a5569329 --- /dev/null +++ b/src/test/java/io/kuzzle/test/API/Controllers/CollectionTest.java @@ -0,0 +1,514 @@ +package io.kuzzle.test.API.Controllers; + +import com.google.gson.internal.LazilyParsedNumber; +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Options.SearchOptions; +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.ProtocolState; +import io.kuzzle.sdk.Protocol.WebSocket; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; + +public class CollectionTest { + + private AbstractProtocol networkProtocol = Mockito.mock(WebSocket.class); + + @Test + public void existsCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getCollectionController().exists(index, collection); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "exists"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + } + + @Test(expected = NotConnectedException.class) + public void existsCollectionShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getCollectionController().exists(index, collection); + } + + @Test + public void truncateCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getCollectionController().truncate(index, collection); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "truncate"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + } + + @Test(expected = NotConnectedException.class) + public void truncateCollectionShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getCollectionController().truncate(index, collection); + } + + @Test + public void createCollectionTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getCollectionController().create(index, collection); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "create"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + } + + @Test + public void createCollectionTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + ConcurrentHashMap mapping = new ConcurrentHashMap<>(); + ConcurrentHashMap properties = new ConcurrentHashMap<>(); + ConcurrentHashMap license = new ConcurrentHashMap<>(); + + license.put("type", "keyword"); + properties.put("license", license); + mapping.put("properties", properties); + + kuzzleMock.getCollectionController().create(index, collection, mapping); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "create"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + assertEquals(( + (ConcurrentHashMap) ( + (ConcurrentHashMap) ( + ((ConcurrentHashMap) + ((arg.getValue()) + .get("body"))) + .get("properties"))) + .get("license")) + .get("type").toString(), "keyword"); + } + + @Test(expected = NotConnectedException.class) + public void createCollectionThrowWhenNotConnected() throws NotConnectedException, InternalException { + + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getCollectionController().create(index, collection); + } + + @Test + public void getMappingCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getCollectionController().getMapping(index, collection); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "getMapping"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + } + + @Test(expected = NotConnectedException.class) + public void getMappingShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getCollectionController().getMapping(index, collection); + } + + @Test + public void refreshCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getCollectionController().refresh(index, collection); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "refresh"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + } + + @Test(expected = NotConnectedException.class) + public void refreshCollectionShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getCollectionController().refresh(index, collection); + } + + @Test + public void deleteSpecificationsCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getCollectionController().deleteSpecifications(index, collection); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "deleteSpecifications"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + } + + @Test(expected = NotConnectedException.class) + public void deleteSpecificationsCollectionThrowWhenNotConnected() throws NotConnectedException, InternalException { + + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getCollectionController().deleteSpecifications(index, collection); + } + + @Test + public void getSpecificationsCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getCollectionController().getSpecifications(index, collection); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "getSpecifications"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + } + + @Test(expected = NotConnectedException.class) + public void getSpecificationsCollectionThrowWhenNotConnected() throws NotConnectedException, InternalException { + + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getCollectionController().getSpecifications(index, collection); + } + + @Test + public void validateSpecificationsCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + ConcurrentHashMap specifications = new ConcurrentHashMap<>(); + ConcurrentHashMap fields = new ConcurrentHashMap<>(); + ConcurrentHashMap license = new ConcurrentHashMap<>(); + + specifications.put("strict", false); + license.put("mandatory", true); + license.put("type", "string"); + fields.put("license", license); + specifications.put("fields", fields); + + kuzzleMock.getCollectionController().validateSpecifications(index, collection, specifications); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "validateSpecifications"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + assertEquals(( + (ConcurrentHashMap) ( + (ConcurrentHashMap) ( + ((ConcurrentHashMap) + ((arg.getValue()) + .get("body"))) + .get("fields"))) + .get("license")) + .get("type").toString(), "string"); + } + + @Test(expected = NotConnectedException.class) + public void validateSpecificationsCollectionThrowWhenNotConnected() throws NotConnectedException, InternalException { + + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap specifications = new ConcurrentHashMap<>(); + + kuzzleMock.getCollectionController().validateSpecifications(index, collection, specifications); + } + + @Test + public void updateSpecificationsCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + ConcurrentHashMap specifications = new ConcurrentHashMap<>(); + ConcurrentHashMap fields = new ConcurrentHashMap<>(); + ConcurrentHashMap license = new ConcurrentHashMap<>(); + + specifications.put("strict", false); + license.put("mandatory", true); + license.put("type", "string"); + fields.put("license", license); + specifications.put("fields", fields); + + kuzzleMock.getCollectionController().updateSpecifications(index, collection, specifications); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "updateSpecifications"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + assertEquals(( + (ConcurrentHashMap) ( + (ConcurrentHashMap) ( + ((ConcurrentHashMap) + ((arg.getValue()) + .get("body"))) + .get("fields"))) + .get("license")) + .get("type").toString(), "string"); + } + + @Test(expected = NotConnectedException.class) + public void updateSpecificationsCollectionThrowWhenNotConnected() throws NotConnectedException, InternalException { + + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap specifications = new ConcurrentHashMap<>(); + + kuzzleMock.getCollectionController().updateSpecifications(index, collection, specifications); + } + + @Test + public void searchSpecificationsTestA() throws NotConnectedException, InternalException, ExecutionException, InterruptedException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + query.put("match", match); + searchQuery.put("query", query); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + CompletableFuture queryResponse = new CompletableFuture<>(); + + Response r = new Response(); + r.result = new ConcurrentHashMap(); + ((ConcurrentHashMap) r.result).put("aggregations", new ConcurrentHashMap()); + ((ConcurrentHashMap) r.result).put("total", new LazilyParsedNumber("1")); + ((ConcurrentHashMap) r.result).put("scrollId", ""); + ((ConcurrentHashMap) r.result).put("hits", new ArrayList>()); + doReturn(queryResponse).when(kuzzleMock).query(any(ConcurrentHashMap.class)); + + new Thread(() -> { + try { + kuzzleMock.getCollectionController().searchSpecifications(searchQuery); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + queryResponse.complete(r); + Thread.sleep(1000); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "searchSpecifications"); + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + + } + + @Test + public void searchSpecificationsTestB() throws NotConnectedException, InternalException, ExecutionException, InterruptedException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + SearchOptions options = new SearchOptions(); + options.setSize(10); + options.setFrom(0); + options.setScroll("30s"); + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + query.put("match", match); + searchQuery.put("query", query); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + CompletableFuture queryResponse = new CompletableFuture<>(); + + Response r = new Response(); + r.result = new ConcurrentHashMap(); + ((ConcurrentHashMap) r.result).put("aggregations", new ConcurrentHashMap()); + ((ConcurrentHashMap) r.result).put("total", new LazilyParsedNumber("1")); + ((ConcurrentHashMap) r.result).put("scrollId", ""); + ((ConcurrentHashMap) r.result).put("hits", new ArrayList>()); + doReturn(queryResponse).when(kuzzleMock).query(any(ConcurrentHashMap.class)); + + new Thread(() -> { + try { + kuzzleMock.getCollectionController().searchSpecifications(searchQuery, options); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + queryResponse.complete(r); + Thread.sleep(1000); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "searchSpecifications"); + assertEquals((arg.getValue()).getNumber("from"), 0); + assertEquals((arg.getValue()).getNumber("size"), 10); + assertEquals((arg.getValue()).getString("scroll"), "30s"); + + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + + } + + @Test(expected = NotConnectedException.class) + public void searchSpecificationsShouldThrowWhenNotConnected() throws NotConnectedException, InternalException, ExecutionException, InterruptedException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + searchQuery.put("match", match); + + kuzzleMock.getCollectionController().searchSpecifications(searchQuery); + } + + @Test + public void listCollectionTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getCollectionController().list(index); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "collection"); + assertEquals((arg.getValue()).getString("action"), "list"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + } + + @Test(expected = NotConnectedException.class) + public void listCollectionShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + + kuzzleMock.getCollectionController().list(index); + } +} diff --git a/src/test/java/io/kuzzle/test/API/Controllers/DocumentTest/DocumentTest.java b/src/test/java/io/kuzzle/test/API/Controllers/DocumentTest/DocumentTest.java new file mode 100644 index 00000000..33b1ff61 --- /dev/null +++ b/src/test/java/io/kuzzle/test/API/Controllers/DocumentTest/DocumentTest.java @@ -0,0 +1,1303 @@ +package io.kuzzle.test.API.Controllers.DocumentTest; + +import com.google.gson.internal.LazilyParsedNumber; +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; + +import io.kuzzle.sdk.Options.SearchOptions; +import io.kuzzle.sdk.Options.UpdateOptions; +import io.kuzzle.sdk.Options.CreateOptions; + +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.ProtocolState; +import io.kuzzle.sdk.Protocol.WebSocket; + +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; + +import java.lang.Thread; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +public class DocumentTest { + + private AbstractProtocol networkProtocol = Mockito.mock(WebSocket.class); + + @Test + public void getDocumentTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().get(index, collection, "some-id"); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "get"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + } + + @Test(expected = NotConnectedException.class) + public void getDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getDocumentController().get(index, collection, "some-id"); + } + + + @Test + public void createDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + CreateOptions options = new CreateOptions(); + options.setId("some-id"); + options.setWaitForRefresh(true); + + kuzzleMock.getDocumentController().create(index, collection, document, options); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "create"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("nickname").toString(), "El angel de la muerte que hace el JAVA"); + } + + @Test + public void createDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().create(index, collection, document); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "create"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), null); + assertEquals(((KuzzleMap) arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("nickname").toString(), "El angel de la muerte que hace el JAVA"); + } + + @Test(expected = NotConnectedException.class) + public void createDocumentThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + kuzzleMock.getDocumentController().create(index, collection, document); + } + + @Test + public void createOrReplaceDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + kuzzleMock.getDocumentController().createOrReplace(index, collection, "some-id", document, true); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "createOrReplace"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("nickname").toString(), "El angel de la muerte que hace el JAVA"); + } + + @Test + public void createOrReplaceDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + kuzzleMock.getDocumentController().createOrReplace(index, collection, "some-id", document); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "createOrReplace"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getString("waitForRefresh"), null); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("nickname").toString(), "El angel de la muerte que hace el JAVA"); + } + + @Test(expected = NotConnectedException.class) + public void createOrReplaceDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + kuzzleMock.getDocumentController().createOrReplace(index, collection, "some-id", document); + } + + @Test + public void udpateDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + + UpdateOptions options = new UpdateOptions(); + options.setWaitForRefresh(true); + options.setSource(true); + options.setRetryOnConflict(1); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().update(index, collection, "some-id", document, options); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "update"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getNumber("retryOnConflict"), 1); + assertEquals(((KuzzleMap) arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((KuzzleMap) arg.getValue()).getBoolean("source"), true); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + } + + @Test + public void udpateDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + + document.put("name", "Yoann"); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().update(index, collection, "some-id", document); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "update"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getNumber("retryOnConflict"), null); + assertEquals(((KuzzleMap) arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((KuzzleMap) arg.getValue()).getBoolean("source"), null); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + } + + @Test(expected = NotConnectedException.class) + public void updateShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + String id = "some-id"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + + UpdateOptions options = new UpdateOptions(); + options.setWaitForRefresh(false); + options.setSource(true); + options.setRetryOnConflict(1); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().update(index, collection, "some-id", document, options); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "update"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getNumber("retryOnConflict"), 1); + assertEquals(((KuzzleMap) arg.getValue()).getBoolean("waitForRefresh"), false); + assertEquals(((KuzzleMap) arg.getValue()).getBoolean("source"), true); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + } + + @Test + public void mCreateDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body1 = new ConcurrentHashMap<>(); + ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body1.put("key1", "value1"); + document1.put("body", body1); + + document2.put("_id", "some-id2"); + body2.put("key2", "value2"); + document2.put("body", body2); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mCreate(index, collection, documents); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mCreate"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(0).get("_id").toString(), "some-id1"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(1).get("_id").toString(), "some-id2"); + } + + @Test + public void mCreateDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body.put("key1", "value1"); + document1.put("body", body); + + document2.put("_id", "some-id2"); + body.put("key2", "value2"); + document2.put("body", body); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mCreate(index, collection, documents, true); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mCreate"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(0).get("_id").toString(), "some-id1"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(1).get("_id").toString(), "some-id2"); + } + + @Test(expected = NotConnectedException.class) + public void mCreateDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body.put("key1", "value1"); + document1.put("body", body); + + document2.put("_id", "some-id2"); + body.put("key2", "value2"); + document2.put("body", body); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + kuzzleMock.getDocumentController().mCreate(index, collection, documents); + } + + @Test + public void mDeleteDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + final ArrayList ids = new ArrayList<>(); + ids.add("some-id1"); + ids.add("some-id2"); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mDelete(index, collection, ids); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mDelete"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ArrayList) (((KuzzleMap) (arg.getValue()).get("body"))).get("ids")).get(0), "some-id1"); + assertEquals(((ArrayList) (((KuzzleMap) (arg.getValue()).get("body"))).get("ids")).get(1), "some-id2"); + } + + @Test + public void mDeleteDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + final ArrayList ids = new ArrayList<>(); + ids.add("some-id1"); + ids.add("some-id2"); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mDelete(index, collection, ids, true); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mDelete"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ArrayList) (((KuzzleMap) (arg.getValue()).get("body"))).get("ids")).get(0), "some-id1"); + assertEquals(((ArrayList) (((KuzzleMap) (arg.getValue()).get("body"))).get("ids")).get(1), "some-id2"); + } + + @Test(expected = NotConnectedException.class) + public void mDeleteDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + final ArrayList ids = new ArrayList<>(); + ids.add("some-id1"); + ids.add("some-id2"); + + kuzzleMock.getDocumentController().mDelete(index, collection, ids); + } + + @Test + public void replaceDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().replace(index, collection, "some-id", document, true); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "replace"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("nickname").toString(), "El angel de la muerte que hace el JAVA"); + } + + @Test + public void replaceDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().replace(index, collection, "some-id", document); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "replace"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("name").toString(), "Yoann"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("nickname").toString(), "El angel de la muerte que hace el JAVA"); + } + + @Test(expected = NotConnectedException.class) + public void replaceDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + document.put("name", "Yoann"); + document.put("nickname", "El angel de la muerte que hace el JAVA"); + + kuzzleMock.getDocumentController().replace(index, collection, "some-id", document); + } + + @Test + public void deleteDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().delete(index, collection, "some-id", true); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "delete"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getString("refresh"), "wait_for"); + } + + @Test + public void deleteDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().delete(index, collection, "some-id"); + Mockito.verify(kuzzleMock, Mockito.times(1)).query((KuzzleMap) arg.capture()); + + assertEquals(((KuzzleMap) arg.getValue()).getString("controller"), "document"); + assertEquals(((KuzzleMap) arg.getValue()).getString("action"), "delete"); + assertEquals(((KuzzleMap) arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((KuzzleMap) arg.getValue()).getString("_id"), "some-id"); + assertEquals(((KuzzleMap) arg.getValue()).getBoolean("waitForRefresh"), null); + } + + @Test(expected = NotConnectedException.class) + public void deleteDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getDocumentController().delete(index, collection, "some-id"); + } + + @Test + public void mGetDocumentTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + final ArrayList ids = new ArrayList<>(); + ids.add("some-id1"); + ids.add("some-id2"); + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mGet(index, collection, ids); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mGet"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((ArrayList) (((KuzzleMap) (arg.getValue()).get("body"))).get("ids")).get(0), "some-id1"); + assertEquals(((ArrayList) (((KuzzleMap) (arg.getValue()).get("body"))).get("ids")).get(1), "some-id2"); + } + + @Test(expected = NotConnectedException.class) + public void mGetDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + final ArrayList ids = new ArrayList<>(); + ids.add("some-id1"); + ids.add("some-id2"); + + kuzzleMock.getDocumentController().mGet(index, collection, ids); + } + + @Test + public void mReplaceDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body1 = new ConcurrentHashMap<>(); + ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body1.put("key1", "value1"); + document1.put("body", body1); + + document2.put("_id", "some-id2"); + body2.put("key2", "value2"); + document2.put("body", body2); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mReplace(index, collection, documents); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mReplace"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(0).get("_id").toString(), "some-id1"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(1).get("_id").toString(), "some-id2"); + } + + @Test + public void mReplaceDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body.put("key1", "value1"); + document1.put("body", body); + + document2.put("_id", "some-id2"); + body.put("key2", "value2"); + document2.put("body", body); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mReplace(index, collection, documents, true); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mReplace"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(0).get("_id").toString(), "some-id1"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(1).get("_id").toString(), "some-id2"); + } + + @Test(expected = NotConnectedException.class) + public void mReplaceDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body.put("key1", "value1"); + document1.put("body", body); + + document2.put("_id", "some-id2"); + body.put("key2", "value2"); + document2.put("body", body); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + kuzzleMock.getDocumentController().mReplace(index, collection, documents); + } + + @Test + public void existsDocumentTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().exists(index, collection, "some-id"); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "exists"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("_id"), "some-id"); + } + + @Test(expected = NotConnectedException.class) + public void existsDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getDocumentController().exists(index, collection, "some-id"); + } + + @Test + public void mUpdateDocumentTestA() throws NotConnectedException, InternalException { + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body1 = new ConcurrentHashMap<>(); + ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body1.put("key1", "value1"); + document1.put("body", body1); + + document2.put("_id", "some-id2"); + body2.put("key2", "value2"); + document2.put("body", body2); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mUpdate(index, collection, documents); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mUpdate"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getNumber("retryOnConflict"), null); + assertEquals((arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(0).get("_id").toString(), "some-id1"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(1).get("_id").toString(), "some-id2"); + } + + @Test + public void mUpdateDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body1 = new ConcurrentHashMap<>(); + ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body1.put("key1", "value1"); + document1.put("body", body1); + + document2.put("_id", "some-id2"); + body2.put("key2", "value2"); + document2.put("body", body2); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + UpdateOptions options = new UpdateOptions(); + options.setRetryOnConflict(0); + options.setWaitForRefresh(true); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mUpdate(index, collection, documents, options); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mUpdate"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getNumber("retryOnConflict"), 0); + assertEquals((arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(0).get("_id").toString(), "some-id1"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(1).get("_id").toString(), "some-id2"); + } + + @Test(expected = NotConnectedException.class) + public void mUpdateDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body1 = new ConcurrentHashMap<>(); + ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body1.put("key1", "value1"); + document1.put("body", body1); + + document2.put("_id", "some-id2"); + body2.put("key2", "value2"); + document2.put("body", body2); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + kuzzleMock.getDocumentController().mUpdate(index, collection, documents); + } + + @Test + public void mCreateOrReplaceDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body1 = new ConcurrentHashMap<>(); + ConcurrentHashMap body2 = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body1.put("key1", "value1"); + document1.put("body", body1); + + document2.put("_id", "some-id2"); + body2.put("key2", "value2"); + document2.put("body", body2); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mCreateOrReplace(index, collection, documents); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mCreateOrReplace"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(0).get("_id").toString(), "some-id1"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(1).get("_id").toString(), "some-id2"); + } + + @Test + public void mCreateOrReplaceDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body.put("key1", "value1"); + document1.put("body", body); + + document2.put("_id", "some-id2"); + body.put("key2", "value2"); + document2.put("body", body); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().mCreateOrReplace(index, collection, documents, true); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "mCreateOrReplace"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(0).get("_id").toString(), "some-id1"); + assertEquals(((ArrayList>) (((KuzzleMap) (arg.getValue()).get("body"))).get("documents")).get(1).get("_id").toString(), "some-id2"); + } + + @Test(expected = NotConnectedException.class) + public void mCreateOrReplaceDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document1 = new ConcurrentHashMap<>(); + ConcurrentHashMap document2 = new ConcurrentHashMap<>(); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + + document1.put("_id", "some-id1"); + body.put("key1", "value1"); + document1.put("body", body); + + document2.put("_id", "some-id2"); + body.put("key2", "value2"); + document2.put("body", body); + + final ArrayList> documents = new ArrayList<>(); + documents.add(document1); + documents.add(document2); + + kuzzleMock.getDocumentController().mCreateOrReplace(index, collection, documents); + } + + @Test + public void deleteByQueryDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + query.put("match", match); + searchQuery.put("query", query); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().deleteByQuery(index, collection, searchQuery); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "deleteByQuery"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + } + + @Test + public void deleteByQueryDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + query.put("match", match); + searchQuery.put("query", query); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().deleteByQuery(index, collection, searchQuery, true); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "deleteByQuery"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("refresh"), "wait_for"); + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + } + + @Test(expected = NotConnectedException.class) + public void deleteByQueryDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + searchQuery.put("match", match); + + kuzzleMock.getDocumentController().deleteByQuery(index, collection, searchQuery); + } + + @Test + public void validateDocumentTest() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + + document.put("Tirion", "Fordring"); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().validate(index, collection, document); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "validate"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((ConcurrentHashMap) (((KuzzleMap) arg.getValue()).get("body"))).get("Tirion").toString(), "Fordring"); + + } + + @Test(expected = NotConnectedException.class) + public void validateDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap document = new ConcurrentHashMap<>(); + + document.put("Tirion", "Fordring"); + + kuzzleMock.getDocumentController().validate(index, collection, document); + } + + @Test + public void countDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleMock.getDocumentController().count(index, collection); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "count"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + } + + @Test + public void countDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + searchQuery.put("match", match); + + kuzzleMock.getDocumentController().count(index, collection, searchQuery); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "count"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getString("collection"), "yellow-taxi"); + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + + } + + @Test(expected = NotConnectedException.class) + public void countDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + kuzzleMock.getDocumentController().count(index, collection); + } + + @Test + public void updateByQueryDocumentTestA() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + searchQuery.put("match", match); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + ConcurrentHashMap changes = new ConcurrentHashMap<>(); + changes.put("Hello", "Mister Anderson"); + + kuzzleMock.getDocumentController().updateByQuery(index, collection, searchQuery, changes); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "updateByQuery"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getBoolean("waitForRefresh"), null); + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + assertEquals((((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("changes")).get("Hello")), "Mister Anderson"); + + } + + @Test + public void updateByQueryDocumentTestB() throws NotConnectedException, InternalException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + searchQuery.put("match", match); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + UpdateOptions options = new UpdateOptions(); + options.setWaitForRefresh(true); + options.setSource(true); + options.setRetryOnConflict(1); + ConcurrentHashMap changes = new ConcurrentHashMap<>(); + changes.put("Hello", "Mister Anderson"); + + kuzzleMock.getDocumentController().updateByQuery(index, collection, searchQuery, changes, options); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "updateByQuery"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getNumber("retryOnConflict"), 1); + assertEquals((arg.getValue()).getString("refresh"), "wait_for"); + assertEquals((arg.getValue()).getBoolean("source"), true); + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + assertEquals((((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("changes")).get("Hello")), "Mister Anderson"); + } + + @Test(expected = NotConnectedException.class) + public void updateByQueryDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + searchQuery.put("match", match); + + ConcurrentHashMap changes = new ConcurrentHashMap<>(); + changes.put("Hello", "Mister Anderson"); + + kuzzleMock.getDocumentController().updateByQuery(index, collection, searchQuery, changes); + } + + @Test + public void searchDocumentTestA() throws NotConnectedException, InternalException, ExecutionException, InterruptedException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + query.put("match", match); + searchQuery.put("query", query); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + CompletableFuture queryResponse = new CompletableFuture<>(); + + Response r = new Response(); + r.result = new ConcurrentHashMap(); + ((ConcurrentHashMap) r.result).put("aggregations", new ConcurrentHashMap()); + ((ConcurrentHashMap) r.result).put("total", new LazilyParsedNumber("1")); + ((ConcurrentHashMap) r.result).put("scrollId", ""); + ((ConcurrentHashMap) r.result).put("hits", new ArrayList>()); + doReturn(queryResponse).when(kuzzleMock).query(any(ConcurrentHashMap.class)); + + new Thread(() -> { + try { + kuzzleMock.getDocumentController().search(index, collection, searchQuery); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + queryResponse.complete(r); + Thread.sleep(1000); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "search"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + + } + + @Test + public void searchDocumentTestB() throws NotConnectedException, InternalException, ExecutionException, InterruptedException { + + Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + SearchOptions options = new SearchOptions(); + options.setSize(10); + options.setFrom(0); + options.setScroll("30s"); + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + ConcurrentHashMap query = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + query.put("match", match); + searchQuery.put("query", query); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + CompletableFuture queryResponse = new CompletableFuture<>(); + + Response r = new Response(); + r.result = new ConcurrentHashMap(); + ((ConcurrentHashMap) r.result).put("aggregations", new ConcurrentHashMap()); + ((ConcurrentHashMap) r.result).put("total", new LazilyParsedNumber("1")); + ((ConcurrentHashMap) r.result).put("scrollId", ""); + ((ConcurrentHashMap) r.result).put("hits", new ArrayList>()); + doReturn(queryResponse).when(kuzzleMock).query(any(ConcurrentHashMap.class)); + + new Thread(() -> { + try { + kuzzleMock.getDocumentController().search(index, collection, searchQuery, options); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + queryResponse.complete(r); + Thread.sleep(1000); + Mockito.verify(kuzzleMock, Mockito.times(1)).query(arg.capture()); + + assertEquals((arg.getValue()).getString("controller"), "document"); + assertEquals((arg.getValue()).getString("action"), "search"); + assertEquals((arg.getValue()).getString("index"), "nyc-open-data"); + assertEquals((arg.getValue()).getNumber("from"), 0); + assertEquals((arg.getValue()).getNumber("size"), 10); + assertEquals((arg.getValue()).getString("scroll"), "30s"); + + assertEquals(((ConcurrentHashMap) ((ConcurrentHashMap) (((KuzzleMap) (arg.getValue()).get("body"))).get("query")).get("match")).get("Hello"), "Clarisse"); + + } + + @Test(expected = NotConnectedException.class) + public void searchDocumentShouldThrowWhenNotConnected() throws NotConnectedException, InternalException, ExecutionException, InterruptedException { + AbstractProtocol fakeNetworkProtocol = Mockito.mock(WebSocket.class); + Mockito.when(fakeNetworkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + Kuzzle kuzzleMock = spy(new Kuzzle(fakeNetworkProtocol)); + String index = "nyc-open-data"; + String collection = "yellow-taxi"; + + ConcurrentHashMap searchQuery = new ConcurrentHashMap<>(); + ConcurrentHashMap match = new ConcurrentHashMap<>(); + match.put("Hello", "Clarisse"); + searchQuery.put("match", match); + + kuzzleMock.getDocumentController().search(index, collection, searchQuery); + } +} diff --git a/src/test/java/io/kuzzle/test/API/Controllers/IndexControllerTest.java b/src/test/java/io/kuzzle/test/API/Controllers/IndexControllerTest.java new file mode 100644 index 00000000..23d79f4f --- /dev/null +++ b/src/test/java/io/kuzzle/test/API/Controllers/IndexControllerTest.java @@ -0,0 +1,98 @@ +package io.kuzzle.test.API.Controllers; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.WebSocket; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +public class IndexControllerTest { + private AbstractProtocol networkProtocol = Mockito.mock(WebSocket.class); + + @Test + public void createTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getIndexController().create("my-index"); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals("index", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("create", ((KuzzleMap) arg.getValue()).getString("action")); + assertEquals("my-index", ((KuzzleMap) arg.getValue()).getString("index")); + } + + @Test + public void deleteTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getIndexController().delete("my-index"); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals("index", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("delete", ((KuzzleMap) arg.getValue()).getString("action")); + assertEquals("my-index", ((KuzzleMap) arg.getValue()).getString("index")); + } + + @Test + public void existsTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getIndexController().exists("my-index"); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals("index", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("exists", ((KuzzleMap) arg.getValue()).getString("action")); + assertEquals("my-index", ((KuzzleMap) arg.getValue()).getString("index")); + } + + @Test + public void listTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getIndexController().list(); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals("index", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("list", ((KuzzleMap) arg.getValue()).getString("action")); + } + + @Test + public void mDeleteTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + ArrayList indexes = new ArrayList<>(); + indexes.add("index1"); + indexes.add("index2"); + + kuzzleSpy.getIndexController().mDelete(indexes); + verify(kuzzleSpy, times(1)).query((KuzzleMap) arg.capture()); + + assertEquals("index", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("mDelete", ((KuzzleMap) arg.getValue()).getString("action")); + assertEquals("index1", ((ArrayList)((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("indexes")).get(0)); + assertEquals("index2", ((ArrayList)((ConcurrentHashMap)(((KuzzleMap) arg.getValue()).get("body"))).get("indexes")).get(1)); + } +} diff --git a/src/test/java/io/kuzzle/test/API/Controllers/RealtimeControllerTest.java b/src/test/java/io/kuzzle/test/API/Controllers/RealtimeControllerTest.java new file mode 100644 index 00000000..e078d14c --- /dev/null +++ b/src/test/java/io/kuzzle/test/API/Controllers/RealtimeControllerTest.java @@ -0,0 +1,136 @@ +package io.kuzzle.test.API.Controllers; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Handlers.NotificationHandler; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Options.SubscribeOptions; +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.WebSocket; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +public class RealtimeControllerTest { + private AbstractProtocol networkProtocol = Mockito.mock(WebSocket.class); + + @Test + public void countTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + NotificationHandler notificationHandler = mock(NotificationHandler.class); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getRealtimeController().count("roomId"); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals("realtime", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("count", ((KuzzleMap) arg.getValue()).getString("action")); + assertEquals("roomId", ((KuzzleMap)((KuzzleMap) arg.getValue()).get("body")).getString("roomId")); + } + + @Test + public void publishTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + NotificationHandler notificationHandler = mock(NotificationHandler.class); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + ConcurrentHashMap message = new ConcurrentHashMap<>(); + message.put("foo", "bar"); + + kuzzleSpy.getRealtimeController().publish("index", "collection", message); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals("realtime", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("publish", ((KuzzleMap) arg.getValue()).getString("action")); + assertEquals("index", ((KuzzleMap) arg.getValue()).getString("index")); + assertEquals("collection", ((KuzzleMap) arg.getValue()).getString("collection")); + assertEquals("bar", ((ConcurrentHashMap)((KuzzleMap)((KuzzleMap) arg.getValue()).get("body")).get("message")).get("foo").toString()); + } + + @Test + public void subscribeTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + NotificationHandler notificationHandler = mock(NotificationHandler.class); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getRealtimeController().subscribe("index", "collection", new ConcurrentHashMap<>(), notificationHandler, new SubscribeOptions()); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals("realtime", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("subscribe", ((KuzzleMap) arg.getValue()).getString("action")); + assertEquals("index", ((KuzzleMap) arg.getValue()).getString("index")); + assertEquals("collection", ((KuzzleMap) arg.getValue()).getString("collection")); + } + + @Test + public void notificationHandlerTest() throws NotConnectedException, InternalException, InterruptedException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + NotificationHandler notificationHandler = mock(NotificationHandler.class); + Response response = new Response(); + response.room = "a-room"; + response.result = new ConcurrentHashMap<>(); + ((ConcurrentHashMap)response.result).put("roomId", "a-room"); + ((ConcurrentHashMap)response.result).put("channel", "a-room"); + + CompletableFuture queryResponse = new CompletableFuture(); + + doReturn(queryResponse).when(kuzzleSpy).query(any(ConcurrentHashMap.class)); + + kuzzleSpy.getRealtimeController().subscribe("index", "collection", new ConcurrentHashMap<>(), notificationHandler, new SubscribeOptions()); + queryResponse.complete(response); + Thread.sleep(1000); + kuzzleSpy.trigger(Event.unhandledResponse, response); + verify(notificationHandler).run(any(Response.class)); + } + + @Test + public void notificationHandlerWithoutSubscribeToSelfTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + NotificationHandler notificationHandler = mock(NotificationHandler.class); + Response response = new Response(); + response.room = "a-room"; + response.result = new ConcurrentHashMap<>(); + ((ConcurrentHashMap)response.result).put("roomId", "a-room"); + ((ConcurrentHashMap)response.result).put("channel", "a-room"); + response.Volatile = new ConcurrentHashMap<>(); + response.Volatile.put("sdkInstanceId", kuzzleSpy.instanceId); + + CompletableFuture queryResponse = new CompletableFuture(); + + doReturn(queryResponse).when(kuzzleSpy).query(any(ConcurrentHashMap.class)); + + SubscribeOptions options = new SubscribeOptions(); + options.setSubscribeToSelf(false); + kuzzleSpy.getRealtimeController().subscribe("index", "collection", new ConcurrentHashMap<>(), notificationHandler, options); + queryResponse.complete(response); + kuzzleSpy.trigger(Event.unhandledResponse, response); + verify(notificationHandler, never()).run(any(Response.class)); + } + + @Test + public void unsubscribeTest() throws NotConnectedException, InternalException { + Kuzzle kuzzleSpy = spy(new Kuzzle(networkProtocol)); + NotificationHandler notificationHandler = mock(NotificationHandler.class); + + ArgumentCaptor arg = ArgumentCaptor.forClass(KuzzleMap.class); + + kuzzleSpy.getRealtimeController().unsubscribe("roomId"); + verify(kuzzleSpy).query((KuzzleMap) arg.capture()); + + assertEquals("realtime", ((KuzzleMap) arg.getValue()).getString("controller")); + assertEquals("unsubscribe", ((KuzzleMap) arg.getValue()).getString("action")); + assertEquals("roomId", ((KuzzleMap)((KuzzleMap) arg.getValue()).get("body")).getString("roomId")); + } +} diff --git a/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/KuzzleMapTest.java b/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/KuzzleMapTest.java new file mode 100644 index 00000000..08959ee1 --- /dev/null +++ b/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/KuzzleMapTest.java @@ -0,0 +1,236 @@ +package io.kuzzle.test.CoreClasses.TaskTest; + +import io.kuzzle.sdk.CoreClasses.Maps.KuzzleMap; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.concurrent.ConcurrentHashMap; + +public class KuzzleMapTest { + private KuzzleMap kuzzleMap; + + @Before + public void setup() throws URISyntaxException { + kuzzleMap = new KuzzleMap(); + kuzzleMap.put("String", "String"); + kuzzleMap.put("Number", 0); + kuzzleMap.put("Boolean", false); + kuzzleMap.put("ArrayList", new ArrayList<>()); + kuzzleMap.put("Map", new ConcurrentHashMap<>()); + kuzzleMap.put("KuzzleMap", new KuzzleMap()); + kuzzleMap.put("Null", null); + } + + @Test + public void isString() { + Assert.assertTrue(kuzzleMap.isString("String")); + Assert.assertFalse(kuzzleMap.isString("Number")); + Assert.assertFalse(kuzzleMap.isString("Boolean")); + Assert.assertFalse(kuzzleMap.isString("ArrayList")); + Assert.assertFalse(kuzzleMap.isString("Map")); + Assert.assertFalse(kuzzleMap.isString("KuzzleMap")); + Assert.assertFalse(kuzzleMap.isString("Null")); + Assert.assertFalse(kuzzleMap.isString("UnknownKey")); + } + + @Test + public void isNumber() { + Assert.assertFalse(kuzzleMap.isNumber("String")); + Assert.assertTrue(kuzzleMap.isNumber("Number")); + Assert.assertFalse(kuzzleMap.isNumber("Boolean")); + Assert.assertFalse(kuzzleMap.isNumber("ArrayList")); + Assert.assertFalse(kuzzleMap.isNumber("Map")); + Assert.assertFalse(kuzzleMap.isNumber("KuzzleMap")); + Assert.assertFalse(kuzzleMap.isNumber("Null")); + Assert.assertFalse(kuzzleMap.isNumber("UnknownKey")); + } + + @Test + public void isBoolean() throws Exception { + Assert.assertFalse(kuzzleMap.isBoolean("String")); + Assert.assertFalse(kuzzleMap.isBoolean("Number")); + Assert.assertTrue(kuzzleMap.isBoolean("Boolean")); + Assert.assertFalse(kuzzleMap.isBoolean("ArrayList")); + Assert.assertFalse(kuzzleMap.isBoolean("Map")); + Assert.assertFalse(kuzzleMap.isBoolean("KuzzleMap")); + Assert.assertFalse(kuzzleMap.isBoolean("Null")); + Assert.assertFalse(kuzzleMap.isBoolean("UnknownKey")); + } + + @Test + public void isArrayList() { + Assert.assertFalse(kuzzleMap.isArrayList("String")); + Assert.assertFalse(kuzzleMap.isArrayList("Number")); + Assert.assertFalse(kuzzleMap.isArrayList("Boolean")); + Assert.assertTrue(kuzzleMap.isArrayList("ArrayList")); + Assert.assertFalse(kuzzleMap.isArrayList("Map")); + Assert.assertFalse(kuzzleMap.isArrayList("KuzzleMap")); + Assert.assertFalse(kuzzleMap.isArrayList("Null")); + Assert.assertFalse(kuzzleMap.isArrayList("UnknownKey")); + } + + @Test + public void isMap() { + Assert.assertFalse(kuzzleMap.isMap("String")); + Assert.assertFalse(kuzzleMap.isMap("Number")); + Assert.assertFalse(kuzzleMap.isMap("Boolean")); + Assert.assertFalse(kuzzleMap.isMap("ArrayList")); + Assert.assertTrue(kuzzleMap.isMap("Map")); + Assert.assertTrue(kuzzleMap.isMap("KuzzleMap")); + Assert.assertFalse(kuzzleMap.isMap("Null")); + Assert.assertFalse(kuzzleMap.isMap("UnknownKey")); + } + + @Test + public void isNull() { + Assert.assertFalse(kuzzleMap.isNull("String")); + Assert.assertFalse(kuzzleMap.isNull("Number")); + Assert.assertFalse(kuzzleMap.isNull("Boolean")); + Assert.assertFalse(kuzzleMap.isNull("ArrayList")); + Assert.assertFalse(kuzzleMap.isNull("Map")); + Assert.assertFalse(kuzzleMap.isNull("KuzzleMap")); + Assert.assertTrue(kuzzleMap.isNull("Null")); + Assert.assertFalse(kuzzleMap.isNull("UnknownKey")); + } + + @Test + public void getString() { + Assert.assertNotNull(kuzzleMap.getString("String")); + Assert.assertNull(kuzzleMap.getString("Number")); + Assert.assertNull(kuzzleMap.getString("Boolean")); + Assert.assertNull(kuzzleMap.getString("ArrayList")); + Assert.assertNull(kuzzleMap.getString("Map")); + Assert.assertNull(kuzzleMap.getString("KuzzleMap")); + Assert.assertNull(kuzzleMap.getString("Null")); + Assert.assertNull(kuzzleMap.getString("UnknownKey")); + } + + @Test + public void getNumber() { + Assert.assertNull(kuzzleMap.getNumber("String")); + Assert.assertNotNull(kuzzleMap.getNumber("Number")); + Assert.assertNull(kuzzleMap.getNumber("Boolean")); + Assert.assertNull(kuzzleMap.getNumber("ArrayList")); + Assert.assertNull(kuzzleMap.getNumber("Map")); + Assert.assertNull(kuzzleMap.getNumber("KuzzleMap")); + Assert.assertNull(kuzzleMap.getNumber("Null")); + Assert.assertNull(kuzzleMap.getNumber("UnknownKey")); + } + + @Test + public void getBoolean() { + Assert.assertNull(kuzzleMap.getBoolean("String")); + Assert.assertNull(kuzzleMap.getBoolean("Number")); + Assert.assertNotNull(kuzzleMap.getBoolean("Boolean")); + Assert.assertNull(kuzzleMap.getBoolean("ArrayList")); + Assert.assertNull(kuzzleMap.getBoolean("Map")); + Assert.assertNull(kuzzleMap.getBoolean("KuzzleMap")); + Assert.assertNull(kuzzleMap.getBoolean("Null")); + Assert.assertNull(kuzzleMap.getBoolean("UnknownKey")); + } + + @Test + public void getArrayList() { + Assert.assertNull(kuzzleMap.getArrayList("String")); + Assert.assertNull(kuzzleMap.getArrayList("Number")); + Assert.assertNull(kuzzleMap.getArrayList("Boolean")); + Assert.assertNotNull(kuzzleMap.getArrayList("ArrayList")); + Assert.assertNull(kuzzleMap.getArrayList("Map")); + Assert.assertNull(kuzzleMap.getArrayList("KuzzleMap")); + Assert.assertNull(kuzzleMap.getArrayList("Null")); + Assert.assertNull(kuzzleMap.getArrayList("UnknownKey")); + } + + @Test + public void getMap() { + Assert.assertNull(kuzzleMap.getMap("String")); + Assert.assertNull(kuzzleMap.getMap("Number")); + Assert.assertNull(kuzzleMap.getMap("Boolean")); + Assert.assertNull(kuzzleMap.getMap("ArrayList")); + Assert.assertNotNull(kuzzleMap.getMap("Map")); + Assert.assertNotNull(kuzzleMap.getMap("KuzzleMap")); + Assert.assertNull(kuzzleMap.getMap("Null")); + Assert.assertNull(kuzzleMap.getMap("UnknownKey")); + } + + @Test + public void get() { + Assert.assertTrue(kuzzleMap.get("String") instanceof String); + Assert.assertTrue(kuzzleMap.get("Number") instanceof Number); + Assert.assertTrue(kuzzleMap.get("Boolean") instanceof Boolean); + Assert.assertTrue(kuzzleMap.get("ArrayList") instanceof ArrayList); + Assert.assertTrue(kuzzleMap.get("Map") instanceof ConcurrentHashMap); + Assert.assertTrue(kuzzleMap.get("KuzzleMap") instanceof ConcurrentHashMap); + Assert.assertTrue(kuzzleMap.get("Null") == null); + Assert.assertTrue(kuzzleMap.get("UnknownKey") == null); + } + + @Test + public void optString() { + Assert.assertTrue(kuzzleMap.optString("String", "foo").equals("String")); + Assert.assertTrue(kuzzleMap.optString("Number", "foo").equals("foo")); + Assert.assertTrue(kuzzleMap.optString("Boolean", "foo").equals("foo")); + Assert.assertTrue(kuzzleMap.optString("ArrayList", "foo").equals("foo")); + Assert.assertTrue(kuzzleMap.optString("Map", "foo").equals("foo")); + Assert.assertTrue(kuzzleMap.optString("KuzzleMap", "foo").equals("foo")); + Assert.assertTrue(kuzzleMap.optString("Null", "foo").equals("foo")); + Assert.assertTrue(kuzzleMap.optString("UnknownKey", "foo").equals("foo")); + } + + @Test + public void optNumber() { + Assert.assertTrue(kuzzleMap.optNumber("String", 42).equals(42)); + Assert.assertTrue(kuzzleMap.optNumber("Number", 42).equals(0)); + Assert.assertTrue(kuzzleMap.optNumber("Boolean", 42).equals(42)); + Assert.assertTrue(kuzzleMap.optNumber("ArrayList", 42).equals(42)); + Assert.assertTrue(kuzzleMap.optNumber("Map", 42).equals(42)); + Assert.assertTrue(kuzzleMap.optNumber("KuzzleMap", 42).equals(42)); + Assert.assertTrue(kuzzleMap.optNumber("Null", 42).equals(42)); + Assert.assertTrue(kuzzleMap.optNumber("UnknownKey", 42).equals(42)); + } + + @Test + public void optBoolean() { + Assert.assertTrue(kuzzleMap.optBoolean("String", true).equals(true)); + Assert.assertTrue(kuzzleMap.optBoolean("Number", true).equals(true)); + Assert.assertTrue(kuzzleMap.optBoolean("Boolean", true).equals(false)); + Assert.assertTrue(kuzzleMap.optBoolean("ArrayList", true).equals(true)); + Assert.assertTrue(kuzzleMap.optBoolean("Map", true).equals(true)); + Assert.assertTrue(kuzzleMap.optBoolean("KuzzleMap", true).equals(true)); + Assert.assertTrue(kuzzleMap.optBoolean("Null", true).equals(true)); + Assert.assertTrue(kuzzleMap.optBoolean("UnknownKey", true).equals(true)); + } + + @Test + public void optArrayList() { + ArrayList list = new ArrayList<>(); + list.add(1); + + Assert.assertEquals(kuzzleMap.optArrayList("String", list).hashCode(), list.hashCode()); + Assert.assertEquals(kuzzleMap.optArrayList("Number", list).hashCode(), list.hashCode()); + Assert.assertEquals(kuzzleMap.optArrayList("Boolean", list).hashCode(), list.hashCode()); + Assert.assertNotEquals(kuzzleMap.optArrayList("ArrayList", list).hashCode(), list.hashCode()); + Assert.assertEquals(kuzzleMap.optArrayList("Map", list).hashCode(), list.hashCode()); + Assert.assertEquals(kuzzleMap.optArrayList("KuzzleMap", list).hashCode(), list.hashCode()); + Assert.assertEquals(kuzzleMap.optArrayList("Null", list).hashCode(), list.hashCode()); + Assert.assertEquals(kuzzleMap.optArrayList("UnknownKey", list).hashCode(), list.hashCode()); + } + + @Test + public void optMap() { + KuzzleMap map = new KuzzleMap(); + map.put("Data", 1); + + Assert.assertEquals(kuzzleMap.optMap("String", map).hashCode(), map.hashCode()); + Assert.assertEquals(kuzzleMap.optMap("Number", map).hashCode(), map.hashCode()); + Assert.assertEquals(kuzzleMap.optMap("Boolean", map).hashCode(), map.hashCode()); + Assert.assertEquals(kuzzleMap.optMap("ArrayList", map).hashCode(), map.hashCode()); + Assert.assertNotEquals(kuzzleMap.optMap("Map", map).hashCode(), map.hashCode()); + Assert.assertNotEquals(kuzzleMap.optMap("KuzzleMap", map).hashCode(), map.hashCode()); + Assert.assertEquals(kuzzleMap.optMap("Null", map).hashCode(), map.hashCode()); + Assert.assertEquals(kuzzleMap.optMap("UnknownKey", map).hashCode(), map.hashCode()); + } +} diff --git a/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/SearchResultTest.java b/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/SearchResultTest.java new file mode 100644 index 00000000..b5353882 --- /dev/null +++ b/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/SearchResultTest.java @@ -0,0 +1,92 @@ +package io.kuzzle.test.CoreClasses.TaskTest; + +import com.google.gson.internal.LazilyParsedNumber; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.CoreClasses.SearchResult; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Options.SearchOptions; +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.WebSocket; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; + +import static org.mockito.Mockito.spy; + +public class SearchResultTest { + + private AbstractProtocol networkProtocol = Mockito.mock(WebSocket.class); + + private Kuzzle kuzzleMock = spy(new Kuzzle(networkProtocol)); + private SearchOptions options = new SearchOptions(); + private ConcurrentHashMap request = new ConcurrentHashMap<>(); + private ConcurrentHashMap result = new ConcurrentHashMap<>(); + private ConcurrentHashMap aggregations = new ConcurrentHashMap<>(); + private ArrayList> hits = new ArrayList<>(); + private Response response = new Response(); + + @Test + public void constructorTestA() { + result.put("aggregations", aggregations); + result.put("hits", hits); + result.put("scrollId", ""); + result.put("total", new LazilyParsedNumber("1")); + + response.result = result; + + SearchResult searchResult = new SearchResult(kuzzleMock, request, options, response); + Assert.assertNotNull(searchResult); + } + + @Test + public void constructorTestB() { + result.put("aggregations", aggregations); + result.put("hits", hits); + result.put("scrollId", ""); + result.put("total", new LazilyParsedNumber("1")); + + response.result = result; + + SearchResult searchResult = new SearchResult(kuzzleMock, request, options, response, 10); + Assert.assertNotNull(searchResult); + } + + @Test + public void nextTestA() throws InternalException, ExecutionException, NotConnectedException, InterruptedException { + result.put("aggregations", aggregations); + result.put("hits", hits); + result.put("scrollId", "30s"); + result.put("scrollAction", "scroll"); + result.put("total", new LazilyParsedNumber("10")); + request.put("controller", "document"); + response.result = result; + + SearchResult searchResult = new SearchResult(kuzzleMock, request, options, response, 10); + searchResult = searchResult.next().get(); + Assert.assertNull(searchResult); + } + + @Test + public void nextTestB() throws InternalException, ExecutionException, NotConnectedException, InterruptedException { + result.put("aggregations", aggregations); + result.put("hits", hits); + result.put("scrollAction", "scroll"); + result.put("total", new LazilyParsedNumber("20")); + request.put("controller", "document"); + options.setSize(10); + options.setFrom(30); + ConcurrentHashMap body = new ConcurrentHashMap<>(); + request.put("body", body); + response.result = result; + + SearchResult searchResult = new SearchResult(kuzzleMock, request, options, response, 10); + searchResult = searchResult.next().get(); + Assert.assertNull(searchResult); + } +} diff --git a/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/TaskTests.java b/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/TaskTests.java new file mode 100644 index 00000000..b2ebb046 --- /dev/null +++ b/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/TaskTests.java @@ -0,0 +1,112 @@ +package io.kuzzle.test.CoreClasses.TaskTest; + +import io.kuzzle.sdk.CoreClasses.Task; +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + +public class TaskTests { + @Test + public void constructorTest() { + TestableTask task = new TestableTask<>(); + Assert.assertNotNull(task.getFuture()); + } + + @Test + public void getFutureTest() { + Task task = new Task<>(); + + Assert.assertEquals(CompletableFuture.class, task.getFuture().getClass()); + } + + @Test + public void setExceptionTest() { + TestableTask task = new TestableTask<>(); + task.applyMocks(); + + task.setException(new Exception("foobar")); + + verify(task.mockedFuture, times(1)).completeExceptionally(any(Exception.class)); + } + + @Test + public void isCancelledTest() { + TestableTask task = new TestableTask<>(); + task.applyMocks(); + + when(task.mockedFuture.isCancelled()).thenReturn(true); + + Assert.assertTrue(task.isCancelled()); + + verify(task.mockedFuture, times(1)).isCancelled(); + } + + @Test + public void isDoneTest() { + TestableTask task = new TestableTask<>(); + task.applyMocks(); + + when(task.mockedFuture.isDone()).thenReturn(true); + + Assert.assertTrue(task.isDone()); + + verify(task.mockedFuture, times(1)).isDone(); + } + + @Test + public void isCompletedExceptionallyTest() { + TestableTask task = new TestableTask<>(); + task.applyMocks(); + + when(task.mockedFuture.isCompletedExceptionally()).thenReturn(true); + + Assert.assertTrue(task.isCompletedExceptionally()); + + verify(task.mockedFuture, times(1)).isCompletedExceptionally(); + } + + @Test + public void setCancelledTest() { + TestableTask task = new TestableTask<>(); + task.applyMocks(); + + task.setCancelled(true); + + verify(task.mockedFuture, times(1)).cancel(anyBoolean()); + } + + @Test + public void triggerTest() { + Task task = new Task(); + + final AtomicBoolean success = new AtomicBoolean(false); + + CompletableFuture taskChain = task.getFuture().thenRun(() -> success.set(true)); + + task.trigger(); + + taskChain.join(); + + Assert.assertTrue(success.get()); + } + + @Test + public void triggerWithObjectTest() { + Task task = new Task(); + + final AtomicBoolean success = new AtomicBoolean(false); + + CompletableFuture taskChain = task.getFuture().thenAccept((str) -> success.set(str.equals("foobar"))); + + task.trigger("foobar"); + + taskChain.join(); + + Assert.assertTrue(success.get()); + } +} diff --git a/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/TestableTask.java b/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/TestableTask.java new file mode 100644 index 00000000..0ae5c330 --- /dev/null +++ b/src/test/java/io/kuzzle/test/CoreClasses/TaskTest/TestableTask.java @@ -0,0 +1,22 @@ +package io.kuzzle.test.CoreClasses.TaskTest; + +import io.kuzzle.sdk.CoreClasses.Task; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; + +import static org.mockito.Mockito.mock; + +public class TestableTask extends Task { + public CountDownLatch mockedCountDownLatch = mock(CountDownLatch.class); + public CompletableFuture mockedFuture = mock(CompletableFuture.class); + + public TestableTask() { + super(); + } + + public void applyMocks() { + super.future = mockedFuture; + } +} diff --git a/src/test/java/io/kuzzle/test/EventsTest/EventManagerTests.java b/src/test/java/io/kuzzle/test/EventsTest/EventManagerTests.java new file mode 100644 index 00000000..02bc151b --- /dev/null +++ b/src/test/java/io/kuzzle/test/EventsTest/EventManagerTests.java @@ -0,0 +1,84 @@ +package io.kuzzle.test.EventsTest; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Matchers; + +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Events.EventListener; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +public class EventManagerTests { + + @Test + public void registerRunnableTest() { + MockedEventManager eventManager = new MockedEventManager(); + + eventManager.register(Event.connected, (Object... args) -> { + }); + + Assert.assertEquals(1, eventManager.getListeners().size()); + } + + @Test + public void unregisterRunnableTest() { + MockedEventManager eventManager = new MockedEventManager(); + EventListener listener = (Object... args) -> { + }; + + eventManager.register(Event.connected, listener); + eventManager.unregister(Event.connected, listener); + + Assert.assertEquals(0, eventManager.getListeners().get(Event.connected).size()); + } + + @Test + public void registerDuplicateTest() { + MockedEventManager eventManager = new MockedEventManager(); + + EventListener listener = (Object... args) -> { + }; + eventManager.register(Event.connected, listener); + eventManager.register(Event.connected, listener); + eventManager.register(Event.connected, listener); + eventManager.register(Event.connected, listener); + eventManager.register(Event.connected, listener); + eventManager.register(Event.connected, (Object... args) -> { + }); + + Assert.assertEquals(6, eventManager.getListeners().get(Event.connected).size()); + } + + @Test + public void triggerRunnableTest() { + MockedEventManager eventManager = new MockedEventManager(); + + AtomicBoolean success = new AtomicBoolean(false); + eventManager.register(Event.connected, (Object... args) -> success.set(true)); + + Assert.assertFalse(success.get()); + + eventManager.trigger(Event.connected); + + Assert.assertTrue(success.get()); + } + + @Test + public void triggerListenerTest() { + MockedEventManager eventManager = new MockedEventManager(); + + AtomicBoolean success = new AtomicBoolean(false); + eventManager.register(Event.connected, (Object... args) -> success.set(args[0].toString().equals("foobar"))); + + Assert.assertFalse(success.get()); + + eventManager.trigger(Event.connected, "foobar"); + + Assert.assertTrue(success.get()); + } +} diff --git a/src/test/java/io/kuzzle/test/EventsTest/MockedEventManager.java b/src/test/java/io/kuzzle/test/EventsTest/MockedEventManager.java new file mode 100644 index 00000000..07aac053 --- /dev/null +++ b/src/test/java/io/kuzzle/test/EventsTest/MockedEventManager.java @@ -0,0 +1,19 @@ + +package io.kuzzle.test.EventsTest; + +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Events.EventListener; +import io.kuzzle.sdk.Events.EventManager; + +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +public class MockedEventManager extends EventManager { + public MockedEventManager() { + super(); + } + + public ConcurrentHashMap> getListeners() { + return super.listeners; + } +} \ No newline at end of file diff --git a/src/test/java/io/kuzzle/test/Helpers/DefaultTests.java b/src/test/java/io/kuzzle/test/Helpers/DefaultTests.java new file mode 100644 index 00000000..c4152d3a --- /dev/null +++ b/src/test/java/io/kuzzle/test/Helpers/DefaultTests.java @@ -0,0 +1,24 @@ +package io.kuzzle.test.Helpers; + +import io.kuzzle.sdk.Helpers.Default; +import org.junit.Assert; +import org.junit.Test; + +public class DefaultTests { + + @Test + public void notNullTest() { + String str1 = Default.defaultValue(null, "foobar"); + String str2 = Default.defaultValue("SomeString", "foobar"); + + Integer int1 = Default.defaultValue(null, 42); + Integer int2 = Default.defaultValue(10, 42); + + Assert.assertEquals("foobar", str1); + Assert.assertEquals("SomeString", str2); + + Assert.assertEquals(42, int1.intValue()); + Assert.assertEquals(10, int2.intValue()); + } + +} diff --git a/src/test/java/io/kuzzle/test/KuzzleTests.java b/src/test/java/io/kuzzle/test/KuzzleTests.java new file mode 100644 index 00000000..ad7e389d --- /dev/null +++ b/src/test/java/io/kuzzle/test/KuzzleTests.java @@ -0,0 +1,125 @@ +package io.kuzzle.test; + +import io.kuzzle.sdk.CoreClasses.Json.JsonSerializer; +import io.kuzzle.sdk.CoreClasses.Task; +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Events.EventListener; +import io.kuzzle.sdk.Exceptions.InternalException; +import io.kuzzle.sdk.Exceptions.NotConnectedException; +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.ProtocolState; +import io.kuzzle.sdk.CoreClasses.Responses.ErrorResponse; +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.Protocol.WebSocket; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +import static org.mockito.Mockito.mock; + +import java.net.URISyntaxException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; + +public class KuzzleTests { + private AbstractProtocol networkProtocol = Mockito.mock(WebSocket.class); + private TestableKuzzle kuzzle; + + @Before + public void setup() throws URISyntaxException { + kuzzle = new TestableKuzzle(networkProtocol); + } + + @Test + public void connect() throws Exception { + kuzzle.connect(); + Mockito.verify(networkProtocol, Mockito.times(1)).connect(); + } + + @Test + public void disconnect() throws Exception { + kuzzle.disconnect(); + Mockito.verify(networkProtocol, Mockito.times(1)).disconnect(); + } + + @Test + public void onStateChanged() { + ConcurrentHashMap> requests = kuzzle.getRequests(); + + Task response = new Task<>(); + requests.put("foobar", response); + kuzzle.onStateChanged(ProtocolState.CLOSE); + Assert.assertEquals(0, requests.size()); + Assert.assertTrue(response.isCompletedExceptionally()); + } + + @Test(expected = NotConnectedException.class) + public void queryShouldThrowWhenNotConnected() throws NotConnectedException, InternalException { + Mockito.when(networkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.CLOSE); + + kuzzle.query(new ConcurrentHashMap<>()); + } + + @Test + public void querySuccess() throws NotConnectedException, InternalException { + Mockito.when(networkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.OPEN); + + CompletableFuture response = kuzzle.query(new ConcurrentHashMap<>()); + + Assert.assertNotNull(response); + Mockito.verify(networkProtocol, Mockito.times(1)).send(Matchers.any(ConcurrentHashMap.class)); + } + + @Test(expected = InternalException.class) + public void queryShouldThrowWhenVolatileIsNotConcurrentHashMap() throws NotConnectedException, InternalException { + Mockito.when(networkProtocol.getState()).thenAnswer((Answer) invocation -> ProtocolState.OPEN); + + ConcurrentHashMap payload = new ConcurrentHashMap<>(); + payload.put("volatile", "foobar"); + + kuzzle.query(payload); + } + + @Test + public void onResponseReceivedAndTokenIsExpired() { + ConcurrentHashMap> requests = kuzzle.getRequests(); + EventListener listener = mock(EventListener.class); + + Response response = new Response(); + response.requestId = "foobar"; + response.error = new ErrorResponse(); + response.error.id = "security.token.expired"; + response.error.status = 42; + response.room = "room-id"; + + Task task = new Task<>(); + + requests.put("room-id", task); + + kuzzle.register(Event.tokenExpired, listener); + kuzzle.onResponseReceived(JsonSerializer.serialize(response.toMap())); + + Mockito.verify(listener, Mockito.times(1)).trigger(); + } + + @Test + public void onResponseReceivedAndResponseIsUnhandled() { + ConcurrentHashMap> requests = kuzzle.getRequests(); + EventListener listener = mock(EventListener.class); + + Response response = new Response(); + response.requestId = "foobar"; + + Task task = new Task<>(); + + requests.put("request-id", task); + + kuzzle.register(Event.unhandledResponse, listener); + kuzzle.onResponseReceived(JsonSerializer.serialize(response.toMap())); + + Mockito.verify(listener, Mockito.times(1)).trigger(Matchers.any(Response.class)); + } +} diff --git a/src/test/java/io/kuzzle/test/ProtocolTest/TestableWebSocket.java b/src/test/java/io/kuzzle/test/ProtocolTest/TestableWebSocket.java new file mode 100644 index 00000000..47bef2e5 --- /dev/null +++ b/src/test/java/io/kuzzle/test/ProtocolTest/TestableWebSocket.java @@ -0,0 +1,36 @@ +package io.kuzzle.test.ProtocolTest; + +import io.kuzzle.sdk.Events.Event; +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Protocol.ProtocolState; +import io.kuzzle.sdk.Protocol.WebSocket; +import java.net.URISyntaxException; + +import static org.mockito.Mockito.mock; + +public class TestableWebSocket extends WebSocket { + public int stateChangedCount = 0; + public ProtocolState lastStateDispatched = ProtocolState.CLOSE; + public com.neovisionaries.ws.client.WebSocket mockedSocket = mock(com.neovisionaries.ws.client.WebSocket.class); + + public TestableWebSocket(String host) throws URISyntaxException, IllegalArgumentException { + super(host); + } + + public TestableWebSocket(String host, WebSocketOptions options) throws URISyntaxException, IllegalArgumentException { + super(host, options); + super.register(Event.networkStateChange, (Object... args) -> { + stateChangedCount += 1; + lastStateDispatched = state; + }); + } + + public com.neovisionaries.ws.client.WebSocket getSocket() { + return super.socket; + } + + @Override + protected com.neovisionaries.ws.client.WebSocket createClientSocket() { + return mockedSocket; + } +} diff --git a/src/test/java/io/kuzzle/test/ProtocolTest/WebSocketTests.java b/src/test/java/io/kuzzle/test/ProtocolTest/WebSocketTests.java new file mode 100644 index 00000000..e29a4e37 --- /dev/null +++ b/src/test/java/io/kuzzle/test/ProtocolTest/WebSocketTests.java @@ -0,0 +1,84 @@ +package io.kuzzle.test.ProtocolTest; + +import io.kuzzle.sdk.Options.Protocol.WebSocketOptions; +import io.kuzzle.sdk.Protocol.ProtocolState; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.net.URISyntaxException; + +import static org.mockito.Mockito.*; + +public class WebSocketTests { + private TestableWebSocket socket; + private String host; + private WebSocketOptions options; + + @Before + public void setup() throws URISyntaxException { + host = "foo"; + options = new WebSocketOptions().setPort(1234).setSsl(true); + socket = new TestableWebSocket(host, options); + } + + @Test + public void constructorNotConnected() throws URISyntaxException { + TestableWebSocket ws = new TestableWebSocket(host, options); + + Assert.assertEquals(ProtocolState.CLOSE, ws.getState()); + Assert.assertNull(ws.getSocket()); + } + + @Test(expected = IllegalArgumentException.class) + public void constructorRejectsNullHost() throws URISyntaxException { + TestableWebSocket ws = new TestableWebSocket(null, options); + } + + @Test + public void connectTest() throws Exception { + when(socket.mockedSocket.connect()).thenAnswer(invocation -> null); + + socket.connect(); + + Assert.assertNotNull(socket.getSocket()); + + socket.connect(); + socket.connect(); + socket.connect(); + + verify(socket.mockedSocket, times(1)).connect(); + + Assert.assertEquals(ProtocolState.OPEN, socket.getState()); + Assert.assertEquals(1, socket.stateChangedCount); + Assert.assertEquals(ProtocolState.OPEN, socket.lastStateDispatched); + } + + @Test + public void disconnectTest() throws Exception { + when(socket.mockedSocket.connect()).thenAnswer(invocation -> null); + + socket.connect(); + + Assert.assertEquals(ProtocolState.OPEN, socket.getState()); + Assert.assertEquals(1, socket.stateChangedCount); + Assert.assertEquals(ProtocolState.OPEN, socket.lastStateDispatched); + + socket.disconnect(); + socket.disconnect(); + socket.disconnect(); + + verify(socket.mockedSocket, times(1)).disconnect(); + } + + @Test + public void disconnectWithoutEverConnecting() throws Exception { + Assert.assertEquals(ProtocolState.CLOSE, socket.getState()); + Assert.assertEquals(0, socket.stateChangedCount); + + socket.disconnect(); + + Assert.assertEquals(ProtocolState.CLOSE, socket.getState()); + Assert.assertEquals(0, socket.stateChangedCount); + } +} diff --git a/src/test/java/io/kuzzle/test/TestableKuzzle.java b/src/test/java/io/kuzzle/test/TestableKuzzle.java new file mode 100644 index 00000000..3418edf8 --- /dev/null +++ b/src/test/java/io/kuzzle/test/TestableKuzzle.java @@ -0,0 +1,35 @@ +package io.kuzzle.test; + +import io.kuzzle.sdk.CoreClasses.Responses.Response; +import io.kuzzle.sdk.CoreClasses.Task; +import io.kuzzle.sdk.Events.EventListener; +import io.kuzzle.sdk.Kuzzle; +import io.kuzzle.sdk.Options.KuzzleOptions; +import io.kuzzle.sdk.Protocol.AbstractProtocol; +import io.kuzzle.sdk.Protocol.ProtocolState; + +import java.net.URISyntaxException; +import java.util.concurrent.ConcurrentHashMap; + +public class TestableKuzzle extends Kuzzle { + + public TestableKuzzle(AbstractProtocol networkProtocol) throws URISyntaxException, IllegalArgumentException { + super(networkProtocol); + } + + public TestableKuzzle(AbstractProtocol networkProtocol, KuzzleOptions options) throws IllegalArgumentException { + super(networkProtocol, options); + } + + public void onStateChanged(ProtocolState state) { + super.onStateChanged(state); + } + + public void onResponseReceived(String payload) { + super.onResponseReceived(payload); + } + + public ConcurrentHashMap> getRequests() { + return super.requests; + } +} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/checkTokenTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/checkTokenTest.java deleted file mode 100644 index f51582fc..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/checkTokenTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; -import java.util.Date; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -public class checkTokenTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = IllegalArgumentException.class) - public void testCheckTokenWithIllegalListener() { - kuzzle.checkToken("token", null); - } - - @Test(expected = IllegalArgumentException.class) - public void testCheckTokenWithIllegalToken() { - kuzzle.checkToken(null, mock(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testCheckTokenWithEmptyToken() { - kuzzle.checkToken("", null); - } - - @Test(expected = RuntimeException.class) - public void testCheckTokenException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("valid", true).put("expiresAt", new Date().getTime()))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.checkToken("token", listener); - } - - @Test(expected = RuntimeException.class) - public void testCheckTokenQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.checkToken("token", listener); - } - - @Test - public void testCheckTokenValid() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("valid", true).put("expiresAt", new Date().getTime()))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.checkToken("token-42", mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "checkToken"); - } - - @Test - public void testCheckTokenInvalid() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("valid", false).put("state", "error"))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.checkToken("token-42", mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "checkToken"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/connectionManagementTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/connectionManagementTest.java deleted file mode 100644 index c46d6b37..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/connectionManagementTest.java +++ /dev/null @@ -1,264 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.EventListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.TokenValidity; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.QueryObject; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class connectionManagementTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - kuzzle = new KuzzleExtend("localhost", options, listener); - kuzzle.setSocket(s); - } - - @Test - public void testMaxTTLWithReconnectListener() throws JSONException, URISyntaxException { - Options options = new Options(); - options.setQueueTTL(1); - options.setReplayInterval(1); - options.setAutoReplay(true); - options.setConnect(Mode.MANUAL); - options.setOfflineMode(Mode.AUTO); - options.setAutoReconnect(true); - - QueryObject o = new QueryObject(); - o.setTimestamp(new Date()); - o.setAction("test"); - JSONObject query = new JSONObject("{\"controller\":\"test3\",\"volatile\":{},\"requestId\":\"a476ae61-497e-4338-b4dd-751ac22c6b61\",\"action\":\"test3\",\"collection\":\"test3\"}"); - o.setQuery(query); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - final EventListener listener = mock(EventListener.class); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - listener.trigger(); - return s; - } - }).when(s).connect(); - - kuzzle.setOfflineQueue(o); - - kuzzle.addListener(Event.reconnected, listener); - kuzzle.connect(); - verify(listener, times(1)).trigger(); - } - - @Test - public void testRenewSubscriptionsAfterReconnection() throws URISyntaxException, JSONException, InterruptedException { - Options options = new Options(); - options.setAutoReconnect(true); - options.setQueueTTL(1); - options.setAutoReplay(true); - options.setConnect(Mode.MANUAL); - options.setAutoReconnect(true); - options.setOfflineMode(Mode.AUTO); - KuzzleExtend extended = new KuzzleExtend("localhost", options, null); - extended.setSocket(s); - extended.setState(States.INITIALIZING); - final Kuzzle kuzzleSpy = spy(extended); - - Room - room1 = new Room(new Collection(kuzzleSpy, "test", "index")), - room2 = new Room(new Collection(kuzzleSpy, "test2", "index")); - - room1 = spy(room1); - room2 = spy(room2); - - room1.renew(listener); - room2.renew(listener); - - Map> subscriptions = kuzzle.getSubscriptions(); - subscriptions.put("room", new ConcurrentHashMap()); - subscriptions.get("room").put("42", room1); - subscriptions.get("room").put("43", room2); - - Thread.sleep(2); - kuzzle.renewSubscriptions(); - verify(room1, atLeastOnce()).renew(any(ResponseListener.class)); - verify(room2, atLeastOnce()).renew(any(ResponseListener.class)); - } - - @Test - public void testAutoReconnect() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setAutoReconnect(false); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - kuzzle.disconnect(); - return s; - } - }).when(s).connect(); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - kuzzle = spy(kuzzle); - - kuzzle.connect(); - - // since "connect" is called 2 times with a socket set, disconnect - // is called each time - verify(kuzzle, times(2)).disconnect(); - } - - @Test - public void testConnectNotValid() throws URISyntaxException { - listener = spy(listener); - kuzzle.setState(States.LOGGED_OUT); - kuzzle.setListener(listener); - kuzzle = spy(kuzzle); - kuzzle.connect(); - verify(listener, atLeastOnce()).onSuccess(any(JSONObject.class)); - } - - @Test - public void testOnConnectError() throws URISyntaxException { - listener = spy(listener); - kuzzle.setListener(listener); - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - listener.onError(new JSONObject()); - return null; - } - }).when(s).connect(); - kuzzle.connect(); - verify(listener, times(1)).onError(any(JSONObject.class)); - } - - @Test - public void testConnectEventConnect() throws URISyntaxException { - listener = spy(listener); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - listener.onSuccess(new JSONObject()); - return null; - } - }).when(s).connect(); - kuzzle.connect(); - verify(listener).onSuccess(any(Void.class)); - } - - @Test - public void testDisconnect() { - kuzzle.setState(States.CONNECTED); - assertNotNull(kuzzle.getSocket()); - kuzzle.disconnect(); - assertNull(kuzzle.getSocket()); - } - - @Test(expected = RuntimeException.class) - public void testIsValid() throws Exception { - kuzzle.disconnect(); - kuzzle.isValid(); - } - - @Test - public void testJWTTokenAfterReconnect() throws URISyntaxException { - kuzzle = spy(kuzzle); - kuzzle.setJwtToken("foo"); - TokenValidity tokenValidity = spy(new TokenValidity()); - doReturn(false).when(tokenValidity).isValid(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - kuzzle.setJwtToken((String)null); - ((ResponseListener) invocation.getArguments()[1]).onSuccess(mock(TokenValidity.class)); - return null; - } - }).when(kuzzle).checkToken(eq("foo"), any(ResponseListener.class)); - kuzzle.checkToken("foo", mock(ResponseListener.class)); - assertNull(kuzzle.getJwtToken()); - doReturn(true).when(tokenValidity).isValid(); - kuzzle.setJwtToken("foo"); - kuzzle.connect(); - assertEquals("foo", kuzzle.getJwtToken()); - } - - @Test - public void testJWTTokenErrorAfterReconnect() throws URISyntaxException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - kuzzle.setJwtToken((String)null); - return s; - } - }).when(s).connect(); - kuzzle = spy(kuzzle); - kuzzle.setJwtToken("foo"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((ResponseListener) invocation.getArguments()[1]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).checkToken(eq("foo"), any(ResponseListener.class)); - kuzzle.connect(); - assertNull(kuzzle.getJwtToken()); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/constructorTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/constructorTest.java deleted file mode 100644 index 3fd74802..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/constructorTest.java +++ /dev/null @@ -1,290 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.QueryObject; -import io.kuzzle.sdk.util.QueueFilter; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import main.java.io.kuzzle.sdk.testUtils.QueryArgsHelper; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.*; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.hamcrest.core.IsInstanceOf.instanceOf; - -public class constructorTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setPort(12345); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = IllegalArgumentException.class) - public void testBadUriConnection() throws URISyntaxException { - new Kuzzle(null); - } - - @Test - public void checkSignaturesVariants() throws URISyntaxException { - Kuzzle k = new Kuzzle("localhost"); - assertNotNull(k); - k = new Kuzzle("localhost", new Options()); - assertNotNull(k); - k = new Kuzzle("localhost", listener); - assertNotNull(k); - } - - @Test - public void testKuzzleConstructor() throws URISyntaxException, JSONException { - kuzzle = spy(kuzzle); - assertEquals(kuzzle.getDefaultIndex(), "testIndex"); - assertNotNull(kuzzle); - verify(kuzzle, never()).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } - - @Test - public void testSetHeadersSignaturesVariants() throws JSONException { - kuzzle = spy(kuzzle); - kuzzle.setHeaders(new JSONObject()); - verify(kuzzle).setHeaders(any(JSONObject.class), eq(false)); - } - - @Test(expected = RuntimeException.class) - public void testSetHeaders() throws JSONException { - kuzzle.setHeaders(null, true); - kuzzle.setHeaders(new JSONObject()); - assertNotNull(kuzzle.getHeaders()); - JSONObject content = new JSONObject(); - content.put("foo", "bar"); - kuzzle.setHeaders(content); - assertEquals(kuzzle.getHeaders().getString("foo"), "bar"); - content.put("foo", "baz"); - kuzzle.setHeaders(content, true); - assertEquals(kuzzle.getHeaders().getString("foo"), "baz"); - JSONObject fake = spy(new JSONObject()); - doThrow(JSONException.class).when(fake).keys(); - kuzzle.setHeaders(fake, false); - } - - @Test(expected = RuntimeException.class) - public void testAddHeaders() throws JSONException { - JSONObject query = new JSONObject(); - JSONObject headers = new JSONObject(); - headers.put("testPurpose", "test"); - kuzzle.addHeaders(query, headers); - assertEquals(query.get("testPurpose"), "test"); - JSONObject fake = mock(JSONObject.class); - doThrow(JSONException.class).when(fake).keys(); - kuzzle.addHeaders(new JSONObject(), fake); - } - - @Test - public void testVolatileOptions() throws URISyntaxException, JSONException { - Options options = new Options(); - options.setQueuable(false); - options.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", options, null); - extended.setSocket(s); - extended.setState(States.CONNECTED); - - - JSONObject meta = new JSONObject(); - meta.put("foo", "bar"); - options.setVolatile(meta); - - JSONObject jsonObj = new JSONObject(); - jsonObj.put("requestId", "42"); - - extended.query(QueryArgsHelper.makeQueryArgs("controller", "action"), jsonObj, options, null); - verify(s).send(eq(jsonObj.toString())); - assertEquals(jsonObj.getJSONObject("volatile").getString("foo"), "bar"); - } - - @Test - public void testVolatileInKuzzle() throws JSONException, URISyntaxException { - JSONObject jsonObj = new JSONObject(); - jsonObj.put("requestId", "42"); - JSONObject meta = new JSONObject(); - meta.put("foo", "bar"); - Options options = new Options(); - options.setVolatile(meta); - options.setQueuable(false); - options.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", options, null); - extended.setSocket(s); - extended.setState(States.CONNECTED); - extended.query(QueryArgsHelper.makeQueryArgs("controller", "action"), jsonObj, options); - verify(s).send(eq(jsonObj.toString())); - assertEquals(jsonObj.getJSONObject("volatile").getString("foo"), "bar"); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetDefaultIndexIllegalIndex() { - kuzzle.setDefaultIndex(null); - } - - @Test - public void exposeDefaultIndexGetterSetter() { - assertEquals("testIndex", kuzzle.getDefaultIndex()); - assertThat(kuzzle.setDefaultIndex("foobar"), instanceOf(KuzzleExtend.class)); - assertEquals("foobar", kuzzle.getDefaultIndex()); - } - - @Test - public void exposeJwtTokenGetter() { - assertThat(kuzzle.setJwtToken("foobar"), instanceOf(KuzzleExtend.class)); - assertEquals("foobar", kuzzle.getJwtToken()); - } - - @Test - public void exposeAutoQueueGetterSetter() { - assertThat(kuzzle.setAutoQueue(true), instanceOf(KuzzleExtend.class)); - assertEquals(true, kuzzle.isAutoQueue()); - } - - @Test - public void exposeAutoReconnectGetter() { - assertThat(kuzzle.isAutoReconnect(), instanceOf(boolean.class)); - } - - @Test - public void exposeAutoResubscribeGetterSetter() { - assertThat(kuzzle.setAutoResubscribe(true), instanceOf(KuzzleExtend.class)); - assertEquals(true, kuzzle.isAutoResubscribe()); - } - - @Test - public void exposeAutoReplayGetterSetter() { - assertThat(kuzzle.setAutoReplay(true), instanceOf(KuzzleExtend.class)); - assertEquals(true, kuzzle.isAutoReplay()); - } - - @Test - public void exposeOfflineQueueGetterSetter() { - QueryObject query = new QueryObject(); - assertThat(kuzzle.setOfflineQueue(query), instanceOf(KuzzleExtend.class)); - assertEquals(kuzzle.getOfflineQueue().peek(), query); - } - - @Test - public void exposeQueueFilterGetterSetter() { - QueueFilter qf = new QueueFilter() { - @Override - public boolean filter(JSONObject object) { - return false; - } - }; - - assertThat(kuzzle.setQueueFilter(qf), instanceOf(KuzzleExtend.class)); - assertEquals(qf, kuzzle.getQueueFilter()); - } - - @Test - public void exposeQueueMaxSizeGetterSetter() { - assertThat(kuzzle.setQueueMaxSize(123), instanceOf(KuzzleExtend.class)); - assertEquals(123, kuzzle.getQueueMaxSize()); - } - - @Test - public void ensureQueueMaxSizeIsNeverBelowZero() { - kuzzle.setQueueMaxSize(-4623); - assertEquals(0, kuzzle.getQueueMaxSize()); - } - - @Test - public void exposeQueueTTLGetterSetter() { - assertThat(kuzzle.setQueueTTL(123), instanceOf(KuzzleExtend.class)); - assertEquals(123, kuzzle.getQueueTTL()); - } - - @Test - public void ensureQueueTTLIsNeverBelowZero() { - kuzzle.setQueueTTL(-12); - assertEquals(0, kuzzle.getQueueTTL()); - } - - @Test - public void exposeVolatileGetterSetter() { - JSONObject _volatile = new JSONObject(); - assertThat(kuzzle.setVolatile(_volatile), instanceOf(KuzzleExtend.class)); - assertEquals(_volatile, kuzzle.getVolatile()); - } - - @Test - public void exposeReplayIntervalGetterSetter() { - assertThat(kuzzle.setReplayInterval(123), instanceOf(KuzzleExtend.class)); - assertEquals(123, kuzzle.getReplayInterval()); - } - - @Test - public void ensureReplayIntervalIsNeverBelowZero() { - kuzzle.setReplayInterval(-123); - assertEquals(0, kuzzle.getReplayInterval()); - } - - @Test - public void exposeReconnectionDelayGetter() { - assertThat(kuzzle.getReconnectionDelay(), instanceOf(long.class)); - } - - @Test - public void testGetPort() { - assertEquals(kuzzle.getPort(), 12345); - } - - @Test - public void testSetPort() { - kuzzle = spy(kuzzle); - kuzzle.setPort(1234); - assertEquals(kuzzle.getPort(), 1234); - } - - @Test - public void testGetHost() { - assertEquals("localhost", kuzzle.getHost()); - } - - @Test public void testSetHost() { - kuzzle = spy(kuzzle); - kuzzle.setHost("foobar"); - assertEquals("foobar", kuzzle.getHost()); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/createIndexTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/createIndexTest.java deleted file mode 100644 index 06707f78..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/createIndexTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; -import java.util.Date; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class createIndexTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - @Test(expected = IllegalArgumentException.class) - public void testCreateIndexIllegalIndex() { - kuzzle.checkToken(null, mock(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testCreateIndexException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.createIndex("index", listener); - } - - @Test(expected = RuntimeException.class) - public void testCreateIndexQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.createIndex("index", listener); - } - - @Test - public void testCreateIndex() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("acknowledged", true))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.createIndex("index", mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "index"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "create"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/createMyCredentialsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/createMyCredentialsTest.java deleted file mode 100644 index 600b6f08..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/createMyCredentialsTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class createMyCredentialsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - private JSONObject credentials; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - - try { - credentials = new JSONObject() - .put("foo", "bar"); - } catch (JSONException err) { - throw new RuntimeException(err); - } - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testCreateMyCredentialsException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.createMyCredentials("strategy", credentials, null, listener); - } - - @Test(expected = RuntimeException.class) - public void testCreateMyCredentialsQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.createMyCredentials("strategy", credentials, null, listener); - } - - @Test - public void testCreateMyCredentials() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzle.createMyCredentials("strategy", credentials) - .createMyCredentials("strategy", credentials, mock(Options.class)) - .createMyCredentials("strategy", credentials, mock(ResponseListener.class)) - .createMyCredentials("strategy", credentials, mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(4)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "createMyCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/deleteMyCredentialsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/deleteMyCredentialsTest.java deleted file mode 100644 index 47c23bcc..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/deleteMyCredentialsTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class deleteMyCredentialsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testDeleteMyCredentialsException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.deleteMyCredentials("strategy", null, listener); - } - - @Test(expected = RuntimeException.class) - public void testDeleteMyCredentialsQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.deleteMyCredentials("strategy", null, listener); - } - - @Test - public void testDeleteMyCredentials() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.deleteMyCredentials("strategy") - .deleteMyCredentials("strategy", mock(ResponseListener.class)) - .deleteMyCredentials("strategy", mock(Options.class)) - .deleteMyCredentials("strategy", mock(Options.class), mock(ResponseListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - verify(kuzzle, times(4)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "deleteMyCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/eventSystemTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/eventSystemTest.java deleted file mode 100644 index 6e846c58..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/eventSystemTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.EventListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.util.EventList; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; - -public class eventSystemTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void testAddListener() { - assertEquals(kuzzle.getEventListeners(Event.connected), null); - kuzzle.addListener(Event.connected, mock(EventListener.class)); - assertThat(kuzzle.getEventListeners(Event.connected), instanceOf(EventList.class)); - } - - @Test(expected = NullPointerException.class) - public void testRemoveAllListeners() { - kuzzle.addListener(Event.connected, mock(EventListener.class)); - kuzzle.addListener(Event.connected, mock(EventListener.class)); - kuzzle.addListener(Event.disconnected, mock(EventListener.class)); - kuzzle.addListener(Event.disconnected, mock(EventListener.class)); - assertEquals(kuzzle.getEventListeners(Event.connected).size(), 2); - assertEquals(kuzzle.getEventListeners(Event.disconnected).size(), 2); - kuzzle.removeAllListeners(); - assertEquals(kuzzle.getEventListeners(Event.connected).size(), 0); - assertEquals(kuzzle.getEventListeners(Event.disconnected).size(), 0); - } - - @Test - public void testRemoveAllListenersType() { - kuzzle.addListener(Event.connected, mock(EventListener.class)); - kuzzle.addListener(Event.connected, mock(EventListener.class)); - kuzzle.addListener(Event.disconnected, mock(EventListener.class)); - kuzzle.addListener(Event.disconnected, mock(EventListener.class)); - assertEquals(kuzzle.getEventListeners(Event.connected).size(), 2); - assertEquals(kuzzle.getEventListeners(Event.disconnected).size(), 2); - kuzzle.removeAllListeners(Event.connected); - assertEquals(kuzzle.getEventListeners(Event.connected).size(), 0); - assertEquals(kuzzle.getEventListeners(Event.disconnected).size(), 2); - } - - @Test - public void testRemoveListener() { - EventListener listener1 = mock(EventListener.class); - EventListener listener2 = mock(EventListener.class); - EventListener listener3 = mock(EventListener.class); - EventListener listener4 = mock(EventListener.class); - kuzzle.addListener(Event.disconnected, listener1); - kuzzle.addListener(Event.connected, listener2); - kuzzle.addListener(Event.disconnected, listener3); - kuzzle.addListener(Event.connected, listener4); - assertEquals(kuzzle.getEventListeners(Event.disconnected).get(listener1).getType(), Event.disconnected); - assertEquals(kuzzle.getEventListeners(Event.connected).get(listener2).getType(), Event.connected); - assertEquals(kuzzle.getEventListeners(Event.disconnected).get(listener3).getType(), Event.disconnected); - assertEquals(kuzzle.getEventListeners(Event.connected).get(listener4).getType(), Event.connected); - kuzzle.removeListener(Event.connected, listener2); - assertEquals(kuzzle.getEventListeners(Event.connected).size(), 1); - assertEquals(kuzzle.getEventListeners(Event.disconnected).size(), 2); - assertEquals(kuzzle.getEventListeners(Event.disconnected).get(listener1).getType(), Event.disconnected); - assertEquals(kuzzle.getEventListeners(Event.disconnected).get(listener2), null); - assertEquals(kuzzle.getEventListeners(Event.disconnected).get(listener3).getType(), Event.disconnected); - assertEquals(kuzzle.getEventListeners(Event.connected).get(listener4).getType(), Event.connected); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/factoriesTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/factoriesTest.java deleted file mode 100644 index d0424e4e..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/factoriesTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - -public class factoriesTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void testDataCollectionFactory() { - assertEquals(kuzzle.collection("test").getCollection(), "test"); - assertEquals(kuzzle.collection("test2").getCollection(), "test2"); - } - - @Test(expected = IllegalArgumentException.class) - public void testIllegalDefaultIndex() { - kuzzle.setSuperDefaultIndex(null); - kuzzle.collection("foo"); - } - - @Test(expected = IllegalArgumentException.class) - public void testIllegalIndex() { - kuzzle.setSuperDefaultIndex(null); - kuzzle.collection("collection", null); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getAllStatisticsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/getAllStatisticsTest.java deleted file mode 100644 index dda13a4a..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getAllStatisticsTest.java +++ /dev/null @@ -1,187 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; -import java.util.Iterator; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import main.java.io.kuzzle.sdk.testUtils.QueryArgsHelper; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class getAllStatisticsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - kuzzle.setState(States.CONNECTED); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = IllegalArgumentException.class) - public void testGetAllStatisticsNoListener() { - kuzzle.getAllStatistics(null); - } - - @Test - public void testGetAllStatisticsNoOptions() { - kuzzle = spy(kuzzle); - kuzzle.getAllStatistics(listener); - verify(kuzzle).getAllStatistics(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testGetAllStatisticsException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("hits", mock(JSONObject.class)))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getAllStatistics(listener); - } - - @Test(expected = RuntimeException.class) - public void testGetAllStatisticsQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getAllStatistics(listener); - } - - @Test - public void testGetAllStatsSuccess() throws JSONException { - kuzzle = spy(kuzzle); - final JSONObject response = new JSONObject("{\n" + - " \"total\": 25,\n" + - " \"hits\": [\n" + - " {\n" + - " \"completedRequests\": {\n" + - " \"websocket\": 148,\n" + - " \"rest\": 24,\n" + - " \"mq\": 78\n" + - " },\n" + - " \"failedRequests\": {\n" + - " \"websocket\": 3\n" + - " },\n" + - " \"ongoingRequests\": {\n" + - " \"mq\": 8,\n" + - " \"rest\": 2\n" + - " },\n" + - " \"connections\": {\n" + - " \"websocket\": 13\n" + - " },\n" + - " \"timestamp\": \"2016-01-13T13:46:19.917Z\"\n" + - " }\n" + - " ]\n" + - " }\n"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", response)); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getAllStatistics(new ResponseListener() { - @Override - public void onSuccess(JSONObject[] result) { - try { - for (int i = 0; i < result.length; i++) { - for (Iterator ite = result[i].keys(); ite.hasNext(); ) { - String key = (String) ite.next(); - assertEquals(result[i].get(key), response.getJSONArray("hits").getJSONObject(i).get(key)); - } - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Override - public void onError(JSONObject error) { - - } - }); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "server"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getAllStats"); - } - - @Test - public void testGetAllStatsError() throws JSONException { - kuzzle = spy(kuzzle); - - final JSONObject responseError = new JSONObject(); - responseError.put("error", "rorre"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(responseError); - return null; - } - }).when(kuzzle).query(eq(QueryArgsHelper.makeQueryArgs("server", "getAllStats")), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getAllStatistics(new ResponseListener() { - @Override - public void onSuccess(JSONObject[] object) { - } - - @Override - public void onError(JSONObject error) { - try { - System.out.println(error.toString()); - assertEquals(error.get("error"), "rorre"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "server"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getAllStats"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getAutoRefreshTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/getAutoRefreshTest.java deleted file mode 100644 index 7a90bf73..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getAutoRefreshTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import java.net.URISyntaxException; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class getAutoRefreshTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - - @Before - public void setup() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = mock(ResponseListener.class); - } - - @Test - public void testSignatureVariants() { - Options options = mock(Options.class); - - kuzzle = spy(kuzzle); - - kuzzle.getAutoRefresh(listener); - kuzzle.getAutoRefresh(options, listener); - kuzzle.getAutoRefresh("foo", listener); - - verify(kuzzle, times(3)).getAutoRefresh(any(String.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetAutoRefreshWithIllegalListener() { - kuzzle.getAutoRefresh("index", null, null); - } - - @Test(expected = RuntimeException.class) - public void testGetAutoRefreshException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONArray.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", true)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getAutoRefresh(listener); - } - - @Test(expected = RuntimeException.class) - public void testGetAutoRefreshQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getAutoRefresh(listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetAutoRefreshIllegalDefaultIndex() { - kuzzle = spy(kuzzle); - kuzzle.setSuperDefaultIndex(null); - kuzzle.getAutoRefresh(null, mock(Options.class), listener); - } - - @Test - public void testGetAutoRefresh() throws URISyntaxException, JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", true)); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.getAutoRefresh(listener); - kuzzle.getAutoRefresh(mock(Options.class), listener); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "index"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "getAutoRefresh"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).index, kuzzle.getDefaultIndex()); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getLastStatisticsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/getLastStatisticsTest.java deleted file mode 100644 index acf26fee..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getLastStatisticsTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class getLastStatisticsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - - @Test(expected = RuntimeException.class) - public void testGetLastStatisticsException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getStatistics(listener); - } - - @Test(expected = RuntimeException.class) - public void testGetLastStatisticsQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getStatistics(listener); - } - - @Test - public void testGetLastStatistic() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject("{ result: {\n" + - " completedRequests: {\n" + - " websocket: 148,\n" + - " rest: 24,\n" + - " mq: 78\n" + - " },\n" + - " failedRequests: {\n" + - " websocket: 3\n" + - " },\n" + - " ongoingRequests: {\n" + - " mq: 8,\n" + - " rest: 2\n" + - " },\n" + - " connections: {\n" + - " websocket: 13\n" + - " },\n" + - " \"timestamp\": \"2016-01-13T13:46:19.917Z\"\n" + - " }" + - "}")); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getStatistics(mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "server"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getLastStats"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getMyCredentialsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/getMyCredentialsTest.java deleted file mode 100644 index 7075d906..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getMyCredentialsTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class getMyCredentialsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testGetMyCredentialsException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getMyCredentials("strategy", null, listener); - } - - @Test(expected = RuntimeException.class) - public void testGetMyCredentialsQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getMyCredentials("strategy", null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testListenerNull() { - kuzzle.getMyCredentials(null, null); - } - - @Test - public void testGetMyCredentials() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.getMyCredentials("strategy", mock(ResponseListener.class)); - kuzzle.getMyCredentials("strategy", mock(Options.class), mock(ResponseListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "getMyCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getMyRightsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/getMyRightsTest.java deleted file mode 100644 index 01d4f90e..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getMyRightsTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -public class getMyRightsTest { - - private Kuzzle kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - kuzzle = spy(new KuzzleExtend("localhost", mock(Options.class), mock(ResponseListener.class))); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testIllegalCallback() { - kuzzle.getMyRights(null); - } - - @Test(expected = RuntimeException.class) - public void testQueryException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getMyRights(listener); - } - - @Test(expected = RuntimeException.class) - public void testException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getMyRights(listener); - } - - @Test - public void testGetMyRights() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject() - .put("result", new JSONObject() - .put("hits", new JSONArray())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getMyRights(mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "getMyRights"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getServerInfoTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/getServerInfoTest.java deleted file mode 100644 index fc4abe4f..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getServerInfoTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class getServerInfoTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = IllegalArgumentException.class) - public void testGetServerInfoIllegalListener() { - kuzzle.getServerInfo(null); - } - - @Test - public void testGetServerInfoNoOptions() { - kuzzle = spy(kuzzle); - kuzzle.getServerInfo(mock(ResponseListener.class)); - verify(kuzzle).getServerInfo(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testGetServerInfoException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getServerInfo(listener); - } - - @Test(expected = RuntimeException.class) - public void testGetServerInfoQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getServerInfo(listener); - } - - @Test - public void testGetServerInfo() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener)invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("serverInfo", mock(JSONObject.class)))); - ((OnQueryDoneListener)invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getServerInfo(listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "server"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "info"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getStatisticsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/getStatisticsTest.java deleted file mode 100644 index b7a5876b..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/getStatisticsTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -public class getStatisticsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void checkAllSignaturesVariants() { - kuzzle = spy(kuzzle); - listener = spy(listener); - kuzzle.getStatistics(listener); - kuzzle.getStatistics(System.currentTimeMillis(), listener); - verify(kuzzle).getStatistics(any(Options.class), any(ResponseListener.class)); - verify(kuzzle).getStatistics(any(long.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testGetStatisticsException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONArray.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("hits", mock(JSONArray.class)))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getStatistics(System.currentTimeMillis(), listener); - } - - @Test(expected = RuntimeException.class) - public void testGetStatisticsQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getStatistics(System.currentTimeMillis(), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetStatsIllegalListener() { - kuzzle.getStatistics(System.currentTimeMillis(), null); - } - - @Test - public void testGetStatistics() throws JSONException { - kuzzle = spy(kuzzle); - final JSONObject response = new JSONObject("{ result: {\n" + - " total: 25,\n" + - " hits: [\n" + - " {\n" + - " completedRequests: {\n" + - " websocket: 148,\n" + - " rest: 24,\n" + - " mq: 78\n" + - " },\n" + - " failedRequests: {\n" + - " websocket: 3\n" + - " },\n" + - " ongoingRequests: {\n" + - " mq: 8,\n" + - " rest: 2\n" + - " },\n" + - " connections: {\n" + - " websocket: 13\n" + - " },\n" + - " \"timestamp\": \"2016-01-13T13:46:19.917Z\"\n" + - " }\n" + - " ]\n" + - " }" + - "}"); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.getStatistics(System.currentTimeMillis(), mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "server"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getStats"); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetStatisticsWithoutListener() { - kuzzle.getStatistics(null); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/listCollectionsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/listCollectionsTest.java deleted file mode 100644 index 50f2f395..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/listCollectionsTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class listCollectionsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void testAllSignatureVariants() { - listener = spy(listener); - kuzzle = spy(kuzzle); - kuzzle.listCollections(listener); - kuzzle.listCollections("foo", listener); - kuzzle.listCollections(new Options(), listener); - verify(kuzzle, times(3)).listCollections(any(String.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testListCollectionsWithIllegalListener() { - kuzzle.listCollections("index", null); - } - - @Test(expected = RuntimeException.class) - public void testListCollectionException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONArray.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("collections", mock(JSONArray.class)))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.listCollections(listener); - } - - @Test(expected = RuntimeException.class) - public void testListCollectionQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.listCollections(listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testListCollectionsIllegalDefaultIndex() { - kuzzle = spy(kuzzle); - kuzzle.setSuperDefaultIndex(null); - kuzzle.listCollections(null, mock(Options.class), listener); - } - - @Test - public void testListCollections() throws URISyntaxException, JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("collections", mock(JSONArray.class)))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.listCollections(listener); - kuzzle.listCollections(mock(Options.class), listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "list"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/listIndexesTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/listIndexesTest.java deleted file mode 100644 index 99e30e7f..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/listIndexesTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class listIndexesTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void testAllSignaturesVariant() { - kuzzle = spy(kuzzle); - kuzzle.listIndexes(spy(listener)); - verify(kuzzle).listIndexes(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testListIndexesWithIllegalListener() { - kuzzle.listIndexes(null); - } - - @Test(expected = RuntimeException.class) - public void testListIndexesException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONArray.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("indexes", new JSONArray().put("foo")))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.listIndexes(listener); - } - - @Test(expected = RuntimeException.class) - public void testListIndexesQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.listIndexes(listener); - } - - @Test - public void testListIndexes() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("indexes", new JSONArray().put("foo")))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.listIndexes(listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "index"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "list"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/loginTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/loginTest.java deleted file mode 100644 index 57c6db59..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/loginTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.EventListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class loginTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void checkAllSignaturesVariants() { - JSONObject stubCredentials = new JSONObject(); - kuzzle = spy(kuzzle); - listener = spy(listener); - kuzzle.login("foo", stubCredentials); - kuzzle.login("foo", stubCredentials, 42); - kuzzle.login("foo", stubCredentials, listener); - kuzzle.login("foo"); - kuzzle.login("foo", 42); - kuzzle.login("foo", 42, listener); - kuzzle.login("foo", listener); - verify(kuzzle, times(7)).login(any(String.class), any(JSONObject.class), any(int.class), any(ResponseListener.class)); - } - - @Test - public void testLogin() throws JSONException { - kuzzle = spy(kuzzle); - - ResponseListener listenerSpy = spy(listener); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_type", "type"))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.login("local", new JSONObject().put("username", "username").put("password", "password")); - kuzzle.login("local", new JSONObject().put("username", "username").put("password", "password"), 42); - kuzzle.login("local", new JSONObject().put("username", "username").put("password", "password"), 42, listenerSpy); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "login"); - } - - @Test(expected = IllegalArgumentException.class) - public void testNoStrategy() { - kuzzle.login(null, new JSONObject()); - } - - @Test - public void testLoginAttemptEvent() throws JSONException { - kuzzle = spy(kuzzle); - kuzzle.addListener(Event.loginAttempt, mock(EventListener.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("jwt", "token"))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.login("local", new JSONObject()); - verify(kuzzle, times(2)).emitEvent(any(Event.class), any(Object.class)); - } - - @Test(expected = RuntimeException.class) - public void testLoginQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.login("local", new JSONObject()); - } - - @Test(expected = RuntimeException.class) - public void testLoginOnSuccessException() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("jwt", "token"))); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(kuzzle).setJwtToken(any(String.class)); - kuzzle.login("local", new JSONObject()); - } - - @Test(expected = RuntimeException.class) - public void testLoginOnErrorException() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(kuzzle).emitEvent(any(Event.class), any(Object.class)); - kuzzle.login("local", new JSONObject()); - } - - @Test(expected = RuntimeException.class) - public void testSetJwtTokenException() { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).emitEvent(any(Event.class), any(Object.class)); - kuzzle.setJwtToken("foo"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/logoutTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/logoutTest.java deleted file mode 100644 index 7e87afc2..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/logoutTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class logoutTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void checkAllSignaturesVariants() { - kuzzle = spy(kuzzle); - kuzzle.logout(); - verify(kuzzle).logout(any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testLogoutException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONArray.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("hits", new JSONArray().put("foo")))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.logout(listener); - } - - @Test(expected = RuntimeException.class) - public void testLogoutQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.logout(listener); - } - - @Test - public void testLogout() throws URISyntaxException, JSONException { - kuzzle = spy(kuzzle); - - final JSONObject response = new JSONObject("{\"result\": {\"jwt\": \"jwtToken\"}}"); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.login("local", new JSONObject().put("username", "username").put("password", "password")); - kuzzle.logout(); - kuzzle.logout(mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "logout"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/nowTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/nowTest.java deleted file mode 100644 index 7abdb61f..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/nowTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class nowTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void checkAllSignaturesVariants() { - listener = spy(listener); - kuzzle = spy(kuzzle); - kuzzle.now(listener); - verify(kuzzle).now(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testNowIllegalListener() { - kuzzle = spy(kuzzle); - kuzzle.now(null); - } - - @Test(expected = RuntimeException.class) - public void testNowException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("now", mock(JSONObject.class)))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.now(listener); - } - - @Test(expected = RuntimeException.class) - public void testNowQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.now(listener); - } - - @Test - public void testNow() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener)invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("now", 42424242))); - ((OnQueryDoneListener)invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.now(listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "server"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "now"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/offlineQueueLoaderTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/offlineQueueLoaderTest.java deleted file mode 100644 index d881e2e6..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/offlineQueueLoaderTest.java +++ /dev/null @@ -1,230 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.KuzzleQueue; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.OfflineQueueLoader; -import io.kuzzle.sdk.util.QueryObject; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class offlineQueueLoaderTest { - - private KuzzleExtend kuzzleExtend; - private WebSocketClient s; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - s = mock(WebSocketClient.class); - KuzzleExtend extended = new KuzzleExtend("localhost", options, null); - extended.setSocket(s); - kuzzleExtend = extended; - } - - - @Test - public void testOfflineQueueLoader() throws JSONException, URISyntaxException, InterruptedException { - kuzzleExtend = spy(kuzzleExtend); - kuzzleExtend.setAutoReplay(true); - - Options opts = new Options().setQueuable(true); - kuzzleExtend.setState(States.OFFLINE); - kuzzleExtend.startQueuing(); - - Kuzzle.QueryArgs args = new Kuzzle.QueryArgs(); - args.action = "bar"; - kuzzleExtend.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - - kuzzleExtend.setState(States.READY); - kuzzleExtend.setAutoReplay(false); - OfflineQueueLoader offlineQueueLoader = new OfflineQueueLoader() { - @Override - public KuzzleQueue load() { - KuzzleQueue queue = new KuzzleQueue(); - QueryObject query = new QueryObject(); - try { - query.setQuery(new JSONObject().put("action", "foo").put("requestId", "42").put("controller", "ctrl")); - } catch (JSONException e) { - e.printStackTrace(); - } - queue.addToQueue(query); - return queue; - } - }; - kuzzleExtend.setOfflineQueueLoader(offlineQueueLoader); - - kuzzleExtend.replayQueue(); - ArgumentCaptor argument = ArgumentCaptor.forClass(JSONObject.class); - Thread.sleep(1000); - verify(kuzzleExtend, times(2)).emitRequest((JSONObject) argument.capture(), any(OnQueryDoneListener.class)); - assertEquals(((JSONObject) argument.getAllValues().get(0)).getString("action"), "bar"); - assertEquals(((JSONObject) argument.getAllValues().get(1)).getString("action"), "foo"); - } - - @Test(expected = IllegalArgumentException.class) - public void testOfflineQueueLoaderIllegalRequestId() throws JSONException, URISyntaxException { - - kuzzleExtend = spy(kuzzleExtend); - kuzzleExtend.setAutoReplay(true); - - Options opts = new Options().setQueuable(true); - kuzzleExtend.setState(States.OFFLINE); - kuzzleExtend.startQueuing(); - - Kuzzle.QueryArgs args = new Kuzzle.QueryArgs(); - args.action = "bar"; - kuzzleExtend.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - - kuzzleExtend.setState(States.READY); - kuzzleExtend.setAutoReplay(false); - OfflineQueueLoader offlineQueueLoader = new OfflineQueueLoader() { - @Override - public KuzzleQueue load() { - KuzzleQueue queue = new KuzzleQueue(); - QueryObject query = new QueryObject(); - try { - query.setQuery(new JSONObject().put("action", "foo").put("controller", "ctrl")); - } catch (JSONException e) { - e.printStackTrace(); - } - queue.addToQueue(query); - return queue; - } - }; - kuzzleExtend.setOfflineQueueLoader(offlineQueueLoader); - - kuzzleExtend.replayQueue(); - } - - @Test(expected = IllegalArgumentException.class) - public void testOfflineQueueLoaderIllegalController() throws JSONException, URISyntaxException { - kuzzleExtend = spy(kuzzleExtend); - kuzzleExtend.setAutoReplay(true); - - Options opts = new Options().setQueuable(true); - kuzzleExtend.setState(States.OFFLINE); - kuzzleExtend.startQueuing(); - - Kuzzle.QueryArgs args = new Kuzzle.QueryArgs(); - args.action = "bar"; - kuzzleExtend.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - - kuzzleExtend.setState(States.READY); - kuzzleExtend.setAutoReplay(false); - OfflineQueueLoader offlineQueueLoader = new OfflineQueueLoader() { - @Override - public KuzzleQueue load() { - KuzzleQueue queue = new KuzzleQueue(); - QueryObject query = new QueryObject(); - try { - query.setQuery(new JSONObject().put("action", "foo").put("requestId", "42")); - } catch (JSONException e) { - e.printStackTrace(); - } - queue.addToQueue(query); - return queue; - } - }; - kuzzleExtend.setOfflineQueueLoader(offlineQueueLoader); - - - kuzzleExtend.replayQueue(); - } - - @Test(expected = IllegalArgumentException.class) - public void testOfflineQueueLoaderIllegalAction() throws JSONException, URISyntaxException { - kuzzleExtend = spy(kuzzleExtend); - kuzzleExtend.setAutoReplay(true); - - Options opts = new Options().setQueuable(true); - kuzzleExtend.setState(States.OFFLINE); - kuzzleExtend.startQueuing(); - - Kuzzle.QueryArgs args = new Kuzzle.QueryArgs(); - args.action = "bar"; - kuzzleExtend.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - - kuzzleExtend.setState(States.READY); - kuzzleExtend.setAutoReplay(false); - OfflineQueueLoader offlineQueueLoader = new OfflineQueueLoader() { - @Override - public KuzzleQueue load() { - KuzzleQueue queue = new KuzzleQueue(); - QueryObject query = new QueryObject(); - try { - query.setQuery(new JSONObject().put("requestId", "42").put("controller", "ctrl")); - } catch (JSONException e) { - e.printStackTrace(); - } - queue.addToQueue(query); - return queue; - } - }; - kuzzleExtend.setOfflineQueueLoader(offlineQueueLoader); - - kuzzleExtend.replayQueue(); - } - - @Test - public void testOfflineQueueDuplicateRequestId() throws JSONException, URISyntaxException, InterruptedException { - kuzzleExtend = spy(kuzzleExtend); - kuzzleExtend.setAutoReplay(true); - - Options opts = new Options().setQueuable(true); - kuzzleExtend.setState(States.OFFLINE); - kuzzleExtend.startQueuing(); - - Kuzzle.QueryArgs args = new Kuzzle.QueryArgs(); - args.action = "bar"; - kuzzleExtend.query(args, new JSONObject().put("requestId", "42"), opts, mock(OnQueryDoneListener.class)); - - kuzzleExtend.setState(States.READY); - kuzzleExtend.setAutoReplay(false); - OfflineQueueLoader offlineQueueLoader = new OfflineQueueLoader() { - @Override - public KuzzleQueue load() { - KuzzleQueue queue = new KuzzleQueue(); - QueryObject query = new QueryObject(); - try { - query.setQuery(new JSONObject().put("action", "foo").put("requestId", "42").put("controller", "ctrl")); - } catch (JSONException e) { - e.printStackTrace(); - } - queue.addToQueue(query); - return queue; - } - }; - kuzzleExtend.setOfflineQueueLoader(offlineQueueLoader); - - kuzzleExtend.replayQueue(); - ArgumentCaptor argument = ArgumentCaptor.forClass(JSONObject.class); - Thread.sleep(1000); - verify(kuzzleExtend, times(1)).emitRequest((JSONObject) argument.capture(), any(OnQueryDoneListener.class)); - assertEquals(((JSONObject) argument.getAllValues().get(0)).getString("action"), "bar"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/queryTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/queryTest.java deleted file mode 100644 index 1b66c934..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/queryTest.java +++ /dev/null @@ -1,284 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.QueueFilter; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static junit.framework.Assert.assertNotNull; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class queryTest { - private KuzzleExtend kuzzle; - private WebSocketClient socket = mock(WebSocketClient.class); - private Kuzzle.QueryArgs args; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setState(States.CONNECTED); - kuzzle.setSocket(socket); - - args = new Kuzzle.QueryArgs(); - args.controller = "foo"; - args.action = "bar"; - } - - @Test - public void checkAllSignaturesVariants() throws JSONException { - JSONObject query = new JSONObject(); - OnQueryDoneListener queryListener = mock(OnQueryDoneListener.class); - kuzzle = spy(kuzzle); - kuzzle.query(args, query); - kuzzle.query(args, query, new Options()); - kuzzle.query(args, query, queryListener); - verify(kuzzle, times(3)).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } - - @Test(expected = IllegalStateException.class) - public void shouldThrowIfDisconnected() throws JSONException { - kuzzle.setState(States.DISCONNECTED); - kuzzle.query(args, new JSONObject()); - } - - @Test - public void shouldEmitTheRightRequest() throws JSONException { - kuzzle.query(args, new JSONObject()); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - JSONObject request = new JSONObject(argument.getValue()); - assertEquals(request.getString("controller"), args.controller); - assertEquals(request.getString("action"), args.action); - assertEquals(request.getJSONObject("volatile").length(), 1); - assertEquals(request.has("index"), false); - assertEquals(request.has("collection"), false); - assertEquals(request.has("headers"), false); - assertNotNull(request.getString("requestId")); - } - - @Test - public void shouldAddIndexIfNeeded() throws JSONException { - args.index = "index"; - kuzzle.query(args, new JSONObject()); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - JSONObject request = new JSONObject(argument.getValue()); - assertEquals(request.getString("controller"), args.controller); - assertEquals(request.getString("action"), args.action); - assertEquals(request.getString("index"), args.index); - assertEquals(request.has("collection"), false); - assertEquals(request.has("headers"), false); - assertEquals(request.getJSONObject("volatile").length(), 1); - assertNotNull(request.getString("requestId")); - } - - @Test - public void shouldAddCollectionIfNeeded() throws JSONException { - args.collection = "collection"; - kuzzle.query(args, new JSONObject()); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - JSONObject request = new JSONObject(argument.getValue()); - assertEquals(request.getString("controller"), args.controller); - assertEquals(request.getString("action"), args.action); - assertEquals(request.getString("collection"), args.collection); - assertEquals(request.has("index"), false); - assertEquals(request.has("headers"), false); - assertEquals(request.getJSONObject("volatile").length(), 1); - assertNotNull(request.getString("requestId")); - } - - @Test - public void shouldAddJwtTokenIfNeeded() throws JSONException { - kuzzle.setJwtToken("token"); - kuzzle.query(args, new JSONObject()); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - JSONObject request = new JSONObject(argument.getValue()); - assertEquals(request.getString("controller"), args.controller); - assertEquals(request.getString("action"), args.action); - assertEquals(request.getJSONObject("volatile").length(), 1); - assertEquals(request.has("index"), false); - assertEquals(request.has("collection"), false); - assertNotNull(request.getString("requestId")); - assertEquals(request.getString("jwt"), "token"); - } - - @Test - public void shouldNotAddJwtTokenIfCheckingToken() throws JSONException { - kuzzle.setJwtToken("token"); - args.controller = "auth"; - args.action = "checkToken"; - kuzzle.query(args, new JSONObject()); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - JSONObject request = new JSONObject(argument.getValue()); - assertEquals(request.getString("controller"), args.controller); - assertEquals(request.getString("action"), args.action); - assertEquals(request.getJSONObject("volatile").length(), 1); - assertEquals(request.has("index"), false); - assertEquals(request.has("collection"), false); - assertEquals(request.has("headers"), false); - assertNotNull(request.getString("requestId")); - } - - @Test - public void shouldAddVolatile() throws JSONException { - JSONObject - kuzzleVolatile = new JSONObject().put("foo", "foo").put("bar", "bar"), - optionsVolatile = new JSONObject().put("qux", "qux").put("foo", "bar"); - Options opts = new Options().setVolatile(optionsVolatile); - - kuzzle.setVolatile(kuzzleVolatile); - kuzzle.query(args, new JSONObject(), opts); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - JSONObject _volatile = new JSONObject(argument.getValue()).getJSONObject("volatile"); - assertEquals(_volatile.length(), 4); - assertEquals(_volatile.getString("sdkVersion"), kuzzle.getSdkVersion()); - assertEquals(_volatile.getString("foo"), "bar"); // options take precedence over kuzzle volatile data - assertEquals(_volatile.getString("bar"), "bar"); - assertEquals(_volatile.getString("qux"), "qux"); - } - - @Test - public void shouldSendSdkVersionInVolatile() throws JSONException { - kuzzle.query(args, new JSONObject(), new Options()); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - JSONObject _volatile = new JSONObject(argument.getValue()).getJSONObject("volatile"); - assertEquals(_volatile.length(), 1); - assertEquals(_volatile.getString("sdkVersion"), kuzzle.getSdkVersion()); - } - - @Test - public void shouldAddRefresh() throws JSONException { - String optionsRefresh = "foo"; - Options opts = new Options().setRefresh(optionsRefresh); - - kuzzle.query(args, new JSONObject(), opts); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - String refresh = new JSONObject(argument.getValue()).getString("refresh"); - assertEquals(refresh, optionsRefresh); - } - - @Test - public void shouldAddHeaders() throws JSONException { - JSONObject headers = new JSONObject().put("foo", "bar"); - - kuzzle.setHeaders(headers); - - kuzzle.query(args, new JSONObject()); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - verify(socket).send(argument.capture()); - - assertEquals(new JSONObject(argument.getValue()).getString("foo"), "bar"); - } - - @Test - public void shouldEmitRequestIfConnected() throws JSONException { - Options opts = new Options().setQueuable(false); - kuzzle.setState(States.CONNECTED); - KuzzleExtend kuzzleSpy = spy(kuzzle); - kuzzleSpy.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - verify(kuzzleSpy).emitRequest(any(JSONObject.class), any(OnQueryDoneListener.class)); - assertEquals(kuzzleSpy.getOfflineQueue().size(), 0); - } - - @Test - public void shouldQueueRequestsIfNotConnected() throws JSONException { - Options opts = new Options().setQueuable(true); - kuzzle.setState(States.OFFLINE); - kuzzle.startQueuing(); - - KuzzleExtend kuzzleSpy = spy(kuzzle); - kuzzleSpy.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - verify(kuzzleSpy, never()).emitRequest(any(JSONObject.class), any(OnQueryDoneListener.class)); - assertEquals(kuzzleSpy.getOfflineQueue().size(), 1); - } - - @Test - public void shouldFilterRequestBeforeQueuingIt() throws JSONException { - Options opts = new Options().setQueuable(true); - QueueFilter filter = spy(new QueueFilter() { - @Override - public boolean filter(JSONObject object) { - return false; - } - }); - - kuzzle.setQueueFilter(filter); - kuzzle.setState(States.OFFLINE); - kuzzle.startQueuing(); - - KuzzleExtend kuzzleSpy = spy(kuzzle); - kuzzleSpy.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - verify(kuzzleSpy, never()).emitRequest(any(JSONObject.class), any(OnQueryDoneListener.class)); - verify(filter).filter(any(JSONObject.class)); - assertEquals(kuzzleSpy.getOfflineQueue().size(), 0); - } - - @Test - public void shouldDiscardQueuableRequestWhenNotConnected() throws JSONException { - Options opts = new Options().setQueuable(false); - kuzzle.setState(States.OFFLINE); - OnQueryDoneListener listener = mock(OnQueryDoneListener.class); - - KuzzleExtend kuzzleSpy = spy(kuzzle); - kuzzleSpy.query(args, new JSONObject(), opts, listener); - verify(kuzzleSpy, never()).emitRequest(any(JSONObject.class), any(OnQueryDoneListener.class)); - verify(listener).onError(any(JSONObject.class)); - } - - @Test - public void shouldDiscardNonQueuedRequestWhenNotConnected() throws JSONException { - Options opts = new Options().setQueuable(false); - kuzzle.setState(States.OFFLINE); - kuzzle.stopQueuing(); - OnQueryDoneListener listener = mock(OnQueryDoneListener.class); - - KuzzleExtend kuzzleSpy = spy(kuzzle); - kuzzleSpy.query(args, new JSONObject(), opts, listener); - verify(kuzzleSpy, never()).emitRequest(any(JSONObject.class), any(OnQueryDoneListener.class)); - verify(listener).onError(any(JSONObject.class)); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/queueManagementTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/queueManagementTest.java deleted file mode 100644 index 1115cb42..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/queueManagementTest.java +++ /dev/null @@ -1,209 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; -import java.util.Date; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.QueryObject; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import main.java.io.kuzzle.sdk.testUtils.QueryArgsHelper; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -public class queueManagementTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void testFlushQueue() throws URISyntaxException, JSONException { - Options options = new Options(); - options.setQueueTTL(1); - options.setAutoReplay(true); - options.setConnect(Mode.MANUAL); - options.setAutoReconnect(true); - options.setOfflineMode(Mode.AUTO); - - kuzzle = new KuzzleExtend("localhost", options, null); - QueryObject o = new QueryObject(); - o.setTimestamp(new Date()); - o.setAction("test"); - o.setQuery(new JSONObject("{\"controller\":\"test\",\"volatile\":{},\"requestId\":\"a476ae61-497e-4338-b4dd-751ac22c6b61\",\"action\":\"test\",\"collection\":\"test\"}")); - kuzzle.getOfflineQueue().add(o); - o.setQuery(new JSONObject("{\"controller\":\"test2\",\"volatile\":{},\"requestId\":\"a476ae61-497e-4338-b4dd-751ac22c6b61\",\"action\":\"test2\",\"collection\":\"test2\"}")); - kuzzle.getOfflineQueue().add(o); - assertEquals(kuzzle.getOfflineQueue().size(), 2); - kuzzle.flushQueue(); - assertEquals(kuzzle.getOfflineQueue().size(), 0); - } - - @Test - public void testManualQueuing() throws URISyntaxException, JSONException { - Options options = new Options(); - options.setAutoReconnect(true); - options.setAutoQueue(false); - options.setDefaultIndex("testIndex"); - options.setQueueTTL(10000); - options.setReplayInterval(1); - options.setConnect(Mode.MANUAL); - options.setQueuable(false); - KuzzleExtend extended = new KuzzleExtend("localhost", options, null); - extended.setSocket(s); - extended.setState(States.CONNECTED); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - s.onCloseReceived(); - return s; - } - }).when(s).close(); - extended.connect(); - extended.startQueuing(); - JSONObject query = new JSONObject(); - query.put("requestId", "42"); - extended.query(QueryArgsHelper.makeQueryArgs("test", "test"), query, null, null); - assertEquals(extended.getOfflineQueue().size(), 1); - extended.flushQueue(); - extended.stopQueuing(); - assertEquals(extended.getOfflineQueue().size(), 0); - extended.query(QueryArgsHelper.makeQueryArgs("test", "test"), query, options, null); - assertEquals(extended.getOfflineQueue().size(), 0); - } - - @Test - public void testQueuable() throws URISyntaxException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - s.onCloseReceived(); - return s; - } - }).when(s).close(); - Options options = new Options(); - options.setAutoReconnect(false); - options.setDefaultIndex("testIndex"); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.connect(); - kuzzle.listCollections(mock(ResponseListener.class)); - assertEquals(kuzzle.getOfflineQueue().size(), 1); - kuzzle.flushQueue(); - options.setQueuable(false); - kuzzle.listCollections(options, mock(ResponseListener.class)); - assertEquals(kuzzle.getOfflineQueue().size(), 0); - } - - @Test - public void testQueueMaxSize() throws URISyntaxException, JSONException { - Options options = new Options(); - options.setAutoReconnect(true); - options.setAutoQueue(true); - options.setQueueTTL(1000); - options.setQueueMaxSize(1); - options.setAutoReplay(true); - options.setConnect(Mode.MANUAL); - options.setOfflineMode(Mode.AUTO); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - s.onCloseReceived(); - return s; - } - }).when(s).close(); - kuzzle.connect(); - kuzzle.query(QueryArgsHelper.makeQueryArgs("test", "test"), new JSONObject(), mock(OnQueryDoneListener.class)); - kuzzle.query(QueryArgsHelper.makeQueryArgs("test2", "test2"), new JSONObject()); - kuzzle.query(QueryArgsHelper.makeQueryArgs("test3", "test3"), new JSONObject()); - assertEquals(kuzzle.getOfflineQueue().size(), 1); - assertEquals(kuzzle.getOfflineQueue().peek().getQuery().getString("controller"), "test3"); - verify(s, never()).send(any(String.class)); - } - - - @Test - public void testDequeue() throws URISyntaxException, JSONException { - Options options = new Options(); - options.setAutoReconnect(true); - options.setQueueTTL(10000); - options.setAutoReplay(true); - options.setReplayInterval(1); - options.setConnect(Mode.MANUAL); - options.setOfflineMode(Mode.AUTO); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - s.onCloseReceived(); - return s; - } - }).when(s).close(); - kuzzle.connect(); - - QueryObject o = new QueryObject(); - o.setTimestamp(new Date()); - o.setAction("test"); - - JSONObject query = new JSONObject("{\"controller\":\"test3\",\"volatile\":{},\"requestId\":\"a476ae61-497e-4338-b4dd-751ac22c6b61\",\"action\":\"test3\",\"collection\":\"test3\"}"); - o.setQuery(query); - kuzzle.getOfflineQueue().add(o); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - s.onOpen(); - return s; - } - }).when(s).connect(); - kuzzle.connect(); - kuzzle.setAutoReplay(false); - kuzzle.replayQueue(); - verify(s, atLeastOnce()).send(eq(query.toString())); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/refreshIndexTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/refreshIndexTest.java deleted file mode 100644 index 1b0ba1f9..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/refreshIndexTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import java.net.URISyntaxException; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - - -public class refreshIndexTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setup() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = mock(ResponseListener.class); - } - - @Test - public void testAllSignatureVariants() { - Options options = mock(Options.class); - - kuzzle = spy(kuzzle); - - kuzzle.refreshIndex(); - kuzzle.refreshIndex(options); - kuzzle.refreshIndex(options, listener); - kuzzle.refreshIndex(listener); - kuzzle.refreshIndex("foo"); - kuzzle.refreshIndex("foo", options); - kuzzle.refreshIndex("foo", listener); - - verify(kuzzle, times(7)).refreshIndex(any(String.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testRefreshIndexException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONArray.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_shards", new JSONObject()))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.refreshIndex(listener); - } - - @Test(expected = RuntimeException.class) - public void testRefreshIndexQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.refreshIndex(listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testRefreshIndexIllegalDefaultIndex() { - kuzzle = spy(kuzzle); - kuzzle.setSuperDefaultIndex(null); - kuzzle.refreshIndex(null, mock(Options.class), listener); - } - - @Test - public void testRefreshIndex() throws URISyntaxException, JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_shards", new JSONObject()))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.refreshIndex(); - kuzzle.refreshIndex(listener); - kuzzle.refreshIndex(mock(Options.class), listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(3)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "index"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "refresh"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).index, kuzzle.getDefaultIndex()); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/setAutoRefreshTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/setAutoRefreshTest.java deleted file mode 100644 index 18ca029a..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/setAutoRefreshTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class setAutoRefreshTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - - @Before - public void setup() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = mock(ResponseListener.class); - } - - @Test - public void testSignatureVariants() { - Options options = mock(Options.class); - - kuzzle = spy(kuzzle); - - kuzzle.setAutoRefresh(true); - kuzzle.setAutoRefresh(true, options); - kuzzle.setAutoRefresh(true, options, listener); - kuzzle.setAutoRefresh("foo", true); - kuzzle.setAutoRefresh("foo", true, options); - kuzzle.setAutoRefresh("foo", true, listener); - - verify(kuzzle, times(6)).setAutoRefresh(any(String.class), any(Boolean.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testSetAutoRefreshException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONArray.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", true)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.setAutoRefresh(true, listener); - } - - @Test(expected = RuntimeException.class) - public void testSetAutoRefreshQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.setAutoRefresh(true, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetAutoRefreshIllegalDefaultIndex() { - kuzzle = spy(kuzzle); - kuzzle.setSuperDefaultIndex(null); - kuzzle.setAutoRefresh(null, true, mock(Options.class), listener); - } - - @Test - public void testGetAutoRefresh() throws URISyntaxException, JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", true)); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.setAutoRefresh(true); - kuzzle.setAutoRefresh(true, listener); - kuzzle.setAutoRefresh(true, mock(Options.class), listener); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - ArgumentCaptor request = ArgumentCaptor.forClass(JSONObject.class); - verify(kuzzle, times(3)).query((Kuzzle.QueryArgs) argument.capture(), (JSONObject) request.capture(), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "index"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "setAutoRefresh"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).index, kuzzle.getDefaultIndex()); - assertEquals(((JSONObject) request.getValue()).getJSONObject("body").getBoolean("autoRefresh"), true); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/setJwtTokenTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/setJwtTokenTest.java deleted file mode 100644 index 35d0d5b1..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/setJwtTokenTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Mode; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertNull; -import static junit.framework.Assert.assertTrue; -import static junit.framework.TestCase.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -public class setJwtTokenTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(s); - - kuzzle = spy(kuzzle); - doNothing().when(kuzzle).renewSubscriptions(); - doNothing().when(kuzzle).emitEvent(any(Event.class), any(JSONObject.class)); - } - - @Test - public void shouldHandleStringToken() throws JSONException { - kuzzle.setJwtToken("foobar"); - assertEquals("foobar", kuzzle.getJwtToken()); - - ArgumentCaptor loginResult = ArgumentCaptor.forClass(JSONObject.class); - verify(kuzzle).emitEvent(eq(Event.loginAttempt), (JSONObject)loginResult.capture()); - assertTrue(((JSONObject) loginResult.getValue()).getBoolean("success")); - - verify(kuzzle).renewSubscriptions(); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowWithNullKuzzleResponse() throws JSONException { - kuzzle.setJwtToken((JSONObject) null); - } - - @Test - public void shouldHandleValidKuzzleResponse() throws JSONException { - JSONObject validResponse = new JSONObject() - .put("result", new JSONObject() - .put("jwt", "foobar") - ); - - kuzzle.setJwtToken(validResponse); - assertEquals("foobar", kuzzle.getJwtToken()); - - ArgumentCaptor loginResult = ArgumentCaptor.forClass(JSONObject.class); - verify(kuzzle).emitEvent(eq(Event.loginAttempt), (JSONObject)loginResult.capture()); - assertTrue(((JSONObject) loginResult.getValue()).getBoolean("success")); - - verify(kuzzle).renewSubscriptions(); - } - - @Test - public void shouldHandleInvalidResponse() throws JSONException { - kuzzle.setJwtToken(new JSONObject()); - assertNull(kuzzle.getJwtToken()); - - ArgumentCaptor loginResult = ArgumentCaptor.forClass(JSONObject.class); - verify(kuzzle).emitEvent(eq(Event.loginAttempt), (JSONObject)loginResult.capture()); - assertFalse(((JSONObject) loginResult.getValue()).getBoolean("success")); - - verify(kuzzle, never()).renewSubscriptions(); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/subscriptionsManagementTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/subscriptionsManagementTest.java deleted file mode 100644 index 27a1b127..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/subscriptionsManagementTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.lang.reflect.InvocationTargetException; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - -public class subscriptionsManagementTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void testDeleteSubscription() throws JSONException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { - Map> subscriptions = kuzzle.getSubscriptions(); - - subscriptions.put("foo", new ConcurrentHashMap()); - subscriptions.get("foo").put("bar", mock(Room.class)); - subscriptions.get("foo").put("baz", mock(Room.class)); - subscriptions.get("foo").put("qux", mock(Room.class)); - - kuzzle.deleteSubscription("foobar", "whatever"); - - // there is always a "pending" room ID used to store pending subscriptions - assertEquals(subscriptions.keySet().size(), 2); - assertEquals(subscriptions.get("pending").size(), 0); - assertEquals(subscriptions.get("foo").size(), 3); - - kuzzle.deleteSubscription("foo", "baz"); - - assertEquals(subscriptions.keySet().size(), 2); - assertEquals(subscriptions.get("pending").size(), 0); - assertEquals(subscriptions.get("foo").size(), 2); - - kuzzle.deleteSubscription("foo", "qux"); - - assertEquals(subscriptions.keySet().size(), 2); - assertEquals(subscriptions.get("pending").size(), 0); - assertEquals(subscriptions.get("foo").size(), 1); - - kuzzle.deleteSubscription("foo", "bar"); - - assertEquals(subscriptions.keySet().size(), 1); - assertEquals(subscriptions.get("pending").size(), 0); - assertEquals(subscriptions.containsKey("foo"), false); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/unsetJwtTokenTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/unsetJwtTokenTest.java deleted file mode 100644 index b861f2c2..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/unsetJwtTokenTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.net.URISyntaxException; -import java.util.concurrent.ConcurrentHashMap; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleDataCollectionExtend; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import main.java.io.kuzzle.sdk.testUtils.RoomExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -public class unsetJwtTokenTest { - private KuzzleExtend kuzzle; - private WebSocketClient s; - private ConcurrentHashMap chp = new ConcurrentHashMap<>(); - private Room room; - - @Before - public void setUp() throws URISyntaxException { - kuzzle = new KuzzleExtend("host", mock(Options.class), mock(ResponseListener.class)); - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - s = mock(WebSocketClient.class); - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.getSubscriptions().put("1", chp); - kuzzle.setSocket(s); - - kuzzle = spy(kuzzle); - doNothing().when(kuzzle).emitEvent(any(Event.class), any(JSONObject.class)); - room = spy(new RoomExtend(new KuzzleDataCollectionExtend(kuzzle, "index", "collection"))); - chp.put("2", room); - } - - @Test - public void shouldUnsetTokenAndUnsubscribeAllRoom() { - kuzzle.setJwtTokenWithoutSubscribe("42"); - kuzzle.unsetJwtToken(); - assertEquals(null, kuzzle.getJwtToken()); - verify(room).unsubscribe(); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/updateMyCredentialsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/updateMyCredentialsTest.java deleted file mode 100644 index 9fed407c..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/updateMyCredentialsTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class updateMyCredentialsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - private JSONObject credentials; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - - try { - credentials = new JSONObject() - .put("foo", "bar"); - } catch (JSONException err) { - throw new RuntimeException(err); - } - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testUpdateMyCredentialsException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.updateMyCredentials("strategy", credentials, null, listener); - } - - @Test(expected = RuntimeException.class) - public void testUpdateMyCredentialsQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.updateMyCredentials("strategy", credentials, null, listener); - } - - @Test - public void testUpdateMyCredentials() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzle.updateMyCredentials("strategy", credentials) - .updateMyCredentials("strategy", credentials, mock(Options.class)) - .updateMyCredentials("strategy", credentials, mock(ResponseListener.class)) - .updateMyCredentials("strategy", credentials, mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(4)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "updateMyCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/updateSelfTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/updateSelfTest.java deleted file mode 100644 index f5acfe31..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/updateSelfTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class updateSelfTest { - - Kuzzle kuzzle; - ArgumentCaptor argument; - ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - kuzzle = spy(new Kuzzle("localhost")); - argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - listener = spy(new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); - } - - @Test(expected = RuntimeException.class) - public void testUpdateSelfException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.updateSelf(mock(JSONObject.class)); - } - - @Test - public void testUpdateSelf() throws JSONException { - JSONObject content = new JSONObject(); - content.put("foo", "bar"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_id", "id"))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.updateSelf(content, listener); - kuzzle.updateSelf(content, mock(Options.class)); - kuzzle.updateSelf(content, mock(Options.class), listener); - kuzzle.updateSelf(content); - verify(kuzzle, times(4)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - verify(listener, times(2)).onSuccess(any(JSONObject.class)); - verify(listener, times(2)).onError(any(JSONObject.class)); - assertEquals("auth", ((Kuzzle.QueryArgs)argument.getValue()).controller); - assertEquals("updateSelf", ((Kuzzle.QueryArgs)argument.getValue()).action); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/validateMyCredentialsTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/validateMyCredentialsTest.java deleted file mode 100644 index 9f6178e3..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/validateMyCredentialsTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class validateMyCredentialsTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - private JSONObject credentials; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - - try { - credentials = new JSONObject() - .put("foo", "bar"); - } catch (JSONException err) { - throw new RuntimeException(err); - } - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testValidateMyCredentialsException() throws JSONException { - listener = spy(listener); - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.validateMyCredentials("strategy", credentials, null, listener); - } - - @Test(expected = RuntimeException.class) - public void testValidateMyCredentialsQueryException() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.validateMyCredentials("strategy", credentials, null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testListenerNull() { - kuzzle.validateMyCredentials(null, null, null); - } - - @Test - public void testValidateMyCredentials() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", true)); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzle.validateMyCredentials("strategy", credentials, mock(ResponseListener.class)); - kuzzle.validateMyCredentials("strategy", credentials, mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "validateMyCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/Kuzzle/whoAmiTest.java b/test/main/java/io/kuzzle/sdk/core/Kuzzle/whoAmiTest.java deleted file mode 100644 index f7867539..00000000 --- a/test/main/java/io/kuzzle/sdk/core/Kuzzle/whoAmiTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package main.java.io.kuzzle.sdk.core.Kuzzle; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class whoAmiTest { - private KuzzleExtend kuzzle; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - options.setDefaultIndex("testIndex"); - - kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setSocket(mock(WebSocketClient.class)); - - listener = new ResponseListener() { - @Override - public void onSuccess(Object object) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test - public void testWhoAmIValid() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject() - .put("result", new JSONObject() - .put("_id", "test") - .put("_source", new JSONObject() - .put("profile", new JSONObject() - .put("_id", "admin") - .put("roles", "") - ) - ) - .put("_meta", new JSONObject()) - ) - ); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzle.whoAmI(mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "auth"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getCurrentUser"); - } - - @Test(expected = RuntimeException.class) - public void testWhoAmIInvalid() throws JSONException { - kuzzle = spy(kuzzle); - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.whoAmI(mock(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testWhoAmINoListener() throws JSONException { - kuzzle.whoAmI(null); - } - - @Test(expected = RuntimeException.class) - public void testWhoAmIInvalidResponse() throws JSONException { - kuzzle = spy(kuzzle); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener)invocation.getArguments()[3]).onSuccess(new JSONObject()); - ((OnQueryDoneListener)invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzle.whoAmI(mock(ResponseListener.class)); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/constructorTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/constructorTest.java deleted file mode 100644 index 7d14acec..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/constructorTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class constructorTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - collection.setHeaders(new JSONObject()); - verify(collection).setHeaders(any(JSONObject.class), eq(false)); - } - - @Test(expected = RuntimeException.class) - public void testSetHeaders() throws JSONException { - when(kuzzle.getHeaders()).thenCallRealMethod(); - when(kuzzle.setHeaders(any(JSONObject.class), anyBoolean())).thenCallRealMethod(); - JSONObject content = new JSONObject(); - content.put("foo", "bar"); - collection.setHeaders(content); - assertEquals(collection.getHeaders().getString("foo"), "bar"); - content.put("foo", "baz"); - collection.setHeaders(content, true); - assertEquals(collection.getHeaders().getString("foo"), "baz"); - content.put("bar", "foo"); - collection.setHeaders(content, false); - assertEquals(collection.getHeaders().getString("foo"), "baz"); - assertEquals(collection.getHeaders().getString("bar"), "foo"); - collection.setHeaders(null, false); - assertEquals(collection.getHeaders().getString("foo"), "baz"); - assertEquals(collection.getHeaders().getString("bar"), "foo"); - collection.setHeaders(null, true); - assertEquals(collection.getHeaders().length(), 0); - JSONObject fake = spy(new JSONObject()); - doThrow(JSONException.class).when(fake).keys(); - collection.setHeaders(fake, false); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowIfNoKuzzleInstanceProvided() { - new Collection(null, "foo", "bar"); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowIfNoIndexProvided() { - new Collection(mock(Kuzzle.class), "foo", null); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowIfNoCollectionProvided() { - new Collection(mock(Kuzzle.class), null, "foo"); - } - - @Test(expected = RuntimeException.class) - public void testConstructorException() { - doThrow(JSONException.class).when(kuzzle).getHeaders(); - new Collection(kuzzle, "collections", "foo"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/countTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/countTest.java deleted file mode 100644 index 2ab334f6..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/countTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class countTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - JSONObject filters = mock(JSONObject.class); - collection = spy(collection); - collection.count(filters, listener); - verify(collection).count(eq(filters), eq((Options) null), eq(listener)); - } - - @Test(expected = IllegalArgumentException.class) - public void testCountIllegalListener() { - collection.count(null); - } - - @Test(expected = RuntimeException.class) - public void testCountQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.count(listener); - } - - @Test(expected = RuntimeException.class) - public void testCountException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(Integer.class)); - collection.count(listener); - } - - @Test - public void testCount() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener)invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - JSONObject filters = new JSONObject(); - collection.count(filters, listener); - collection.count(filters, new Options(), listener); - collection.count(listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "count"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/createDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/createDocumentTest.java deleted file mode 100644 index f48c983c..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/createDocumentTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class createDocumentTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() throws JSONException { - Document doc = mock(Document.class); - JSONObject content = new JSONObject(); - String id = "foo"; - Options opts = new Options(); - - collection = spy(collection); - - collection.createDocument(doc); - collection.createDocument(doc, opts); - collection.createDocument(doc, listener); - collection.createDocument(doc, opts, listener); - - collection.createDocument(id, content); - collection.createDocument(id, content, opts); - collection.createDocument(id, content, listener); - collection.createDocument(id, content, opts, listener); - - collection.createDocument(content); - collection.createDocument(content, opts); - collection.createDocument(content, listener); - collection.createDocument(content, opts, listener); - - verify(collection, times(12)).createDocument(any(Document.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testCreateDocumentQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.createDocument(mock(Document.class), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateDocumentIllegalIfExistValue() { - Options opts = new Options(); - - opts.setIfExist("foobar"); - } - - @Test(expected = RuntimeException.class) - public void testCreateDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - collection.createDocument(mock(Document.class), listener); - } - - @Test - public void testCreateDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject result = new JSONObject() - .put("result", new JSONObject() - .put("_id", "foo") - .put("_version", 1337) - .put("_source", new JSONObject()) - .put("_meta", new JSONObject())); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - Document doc = new Document(collection); - doc.setContent("foo", "bar"); - collection.createDocument(doc); - collection.createDocument(doc, mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "create"); - } - - @Test - public void testCreateDocumentWithOptions() throws JSONException { - Document doc = new Document(collection); - doc.setContent("foo", "bar"); - Options options = new Options(); - options.setIfExist("replace"); - collection.createDocument(doc, options); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createOrReplace"); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateDocumentWithIllegalContent() throws JSONException { - collection.createDocument("id", null, mock(Options.class), listener); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/createTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/createTest.java deleted file mode 100644 index 16c1af25..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/createTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import io.kuzzle.sdk.core.Kuzzle.QueryArgs; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class createTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - - collection.create(); - collection.create(mock(Options.class)); - collection.create(listener); - collection.create(mock(Options.class), listener); - collection.create(mock(JSONObject.class)); - collection.create(mock(JSONObject.class), mock(Options.class)); - collection.create(mock(JSONObject.class), listener); - - verify(collection, times(7)).create(any(JSONObject.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testCreateQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.create(listener); - } - - @Test(expected = RuntimeException.class) - public void testCreateException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - return null; - } - }).when(kuzzle).query(any(QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - collection.create(listener); - } - - @Test - public void testCreateWithoutMapping() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - collection.create(new Options(), listener); - collection.create(listener); - collection.create(new Options()); - collection.create(); - - ArgumentCaptor argument = ArgumentCaptor.forClass(QueryArgs.class); - verify(kuzzle, times(4)).query((QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((QueryArgs) argument.getValue()).action, "create"); - } - - @Test - public void testCreateWithMapping() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - JSONObject mapping = new JSONObject().put("foo", "bar"); - - collection.create(mapping); - collection.create(mapping, new Options(), listener); - collection.create(mapping, listener); - collection.create(mapping, new Options()); - - ArgumentCaptor - capturedQargs = ArgumentCaptor.forClass(QueryArgs.class), - capturedMappings = ArgumentCaptor.forClass(JSONObject.class); - - verify(kuzzle, times(4)).query((QueryArgs)capturedQargs.capture(), (JSONObject)capturedMappings.capture(), any(Options.class), any(OnQueryDoneListener.class)); - - assertEquals(((QueryArgs) capturedQargs.getValue()).controller, "collection"); - assertEquals(((QueryArgs) capturedQargs.getValue()).action, "create"); - - String expected = (new JSONObject().put("body", mapping)).toString(); - for (Object m : capturedMappings.getAllValues()) { - assertEquals(expected, m.toString()); - } - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/deleteDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/deleteDocumentTest.java deleted file mode 100644 index 734baba9..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/deleteDocumentTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleDataCollectionExtend; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class deleteDocumentTest { - private Kuzzle kuzzle; - private KuzzleDataCollectionExtend collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new KuzzleDataCollectionExtend(kuzzle, "index", "test"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - JSONObject filters = new JSONObject(); - Options opts = mock(Options.class); - collection = spy(collection); - - collection.deleteDocument("foo"); - collection.deleteDocument("foo", opts); - collection.deleteDocument("foo", listener); - collection.deleteDocument("foo", opts, listener); - - collection.deleteDocument(filters); - collection.deleteDocument(filters, opts); - collection.deleteDocument(filters, listener); - collection.deleteDocument(filters, opts, listener); - - verify(collection, times(8)).deleteDocument(any(String.class), any(JSONObject.class), any(Options.class), any(ResponseListener.class), any(ResponseListener.class)); - } - - @Test - public void testDeleteDocumentByFilter() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("hits", new JSONArray().put("val")))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.deleteDocument(new JSONObject(), listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteByQuery"); - } - - @Test(expected = IllegalArgumentException.class) - public void testDeleteDocumentIllegalId() { - collection.deleteDocument((String) null); - } - - @Test(expected = IllegalArgumentException.class) - public void testDeleteDocumentIllegalFilter() { - collection.deleteDocument((JSONObject) null); - } - - @Test(expected = RuntimeException.class) - public void testDeleteDocumentQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.deleteDocument("id", listener); - } - - @Test(expected = RuntimeException.class) - public void testDeleteDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_id", "id-42"))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.deleteDocument("id", listener); - } - - @Test - public void testDeleteDocumentById() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_id", "id-42"))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.deleteDocument("42", listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "delete"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/deleteSpecificationsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/deleteSpecificationsTest.java deleted file mode 100644 index 8d23701d..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/deleteSpecificationsTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleDataCollectionExtend; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class deleteSpecificationsTest { - private Kuzzle kuzzle; - private KuzzleDataCollectionExtend collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new KuzzleDataCollectionExtend(kuzzle, "index", "test"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkDeleteSpecificationsSignaturesVariants() throws JSONException { - Options opts = mock(Options.class); - collection = spy(collection); - - collection.deleteSpecifications(); - collection.deleteSpecifications(opts); - collection.deleteSpecifications(listener); - collection.deleteSpecifications(opts, listener); - - verify(collection, times(4)).deleteSpecifications(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testDeleteSpecificationsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.deleteSpecifications(listener); - } - - @Test(expected = RuntimeException.class) - public void testDeleteSpecificationsException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("acknowledged", true))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.deleteSpecifications(listener); - } - - @Test - public void testDeleteSpecifications() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("acknowledged", true))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.deleteSpecifications(listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteSpecifications"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/documentExistsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/documentExistsTest.java deleted file mode 100644 index 4f99b28f..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/documentExistsTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class documentExistsTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - collection.documentExists("foo", listener); - verify(collection).documentExists(eq("foo"), eq((Options)null), eq(listener)); - } - - @Test(expected = IllegalArgumentException.class) - public void testDocumentExistsIllegalDocumentId() { - collection.documentExists(null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testDocumentExistsIllegalListener() { - collection.documentExists("id", null); - } - - @Test(expected = RuntimeException.class) - public void testDocumentExistsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.documentExists("id", listener); - } - - @Test(expected = RuntimeException.class) - public void testDocumentExistsException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", true)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.documentExists("id", listener); - } - - @Test - public void testDocumentExists() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess( - new JSONObject() - .put("result", true) - ); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.documentExists("42", mock(ResponseListener.class)); - collection.documentExists("42", new Options(), mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "exists"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/factoriesTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/factoriesTest.java deleted file mode 100644 index 0554dd8f..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/factoriesTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.CollectionMapping; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.core.RoomOptions; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -public class factoriesTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void testRoomFactory() { - assertThat(collection.room(mock(RoomOptions.class)), instanceOf(Room.class)); - assertThat(collection.room(), instanceOf(Room.class)); - } - - @Test - public void testDocumentFactory() throws JSONException { - assertThat(collection.document(), instanceOf(Document.class)); - assertThat(collection.document("id"), instanceOf(Document.class)); - assertThat(collection.document("id", new JSONObject()), instanceOf(Document.class)); - assertThat(collection.document(new JSONObject()), instanceOf(Document.class)); - } - - @Test - public void testDataMappingFactory() { - assertThat(collection.collectionMapping(), instanceOf(CollectionMapping.class)); - assertThat(collection.collectionMapping(new JSONObject()), instanceOf(CollectionMapping.class)); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/fetchDocument.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/fetchDocument.java deleted file mode 100644 index f810d2b2..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/fetchDocument.java +++ /dev/null @@ -1,115 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class fetchDocument { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - collection.fetchDocument("foo", listener); - verify(collection).fetchDocument(eq("foo"), eq((Options)null), eq(listener)); - } - - @Test(expected = IllegalArgumentException.class) - public void testFetchDocumentIllegalDocumentId() { - collection.fetchDocument(null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testFetchDocumentIllegalListener() { - collection.fetchDocument("id", null); - } - - @Test(expected = RuntimeException.class) - public void testFetchDocumentQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.fetchDocument("id", listener); - } - - @Test(expected = RuntimeException.class) - public void testFetchDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.fetchDocument("id", listener); - } - - @Test - public void testFetchDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess( - new JSONObject() - .put("result", new JSONObject() - .put("_id", "foo") - .put("_version", 42) - .put("_source", new JSONObject()) - ) - ); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.fetchDocument("42", mock(ResponseListener.class)); - collection.fetchDocument("42", new Options(), mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "get"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/getMappingTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/getMappingTest.java deleted file mode 100644 index 94caa5d8..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/getMappingTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class getMappingTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - collection.getMapping(listener); - verify(collection).getMapping(eq((Options)null), eq(listener)); - } - - @Test(expected = IllegalArgumentException.class) - public void getMappingIllegalListener() { - collection.getMapping(null); - } - - @Test - public void testGetMapping() throws JSONException { - collection.getMapping(mock(Options.class), mock(ResponseListener.class)); - collection.getMapping(mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getMapping"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/getSpecificationsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/getSpecificationsTest.java deleted file mode 100644 index 9dc088f2..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/getSpecificationsTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class getSpecificationsTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkGetSpecificationsSignaturesVariants() throws JSONException { - collection = spy(collection); - - collection.getSpecifications(mock(Options.class), listener); - collection.getSpecifications(listener); - - verify(collection, times(2)).getSpecifications(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testGetSpecificationsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.getSpecifications(listener); - } - - @Test(expected = RuntimeException.class) - public void testGetSpecificationsException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - collection.getSpecifications(listener); - } - - @Test - public void testGetSpecifications() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess( - new JSONObject() - .put("result", new JSONObject() - .put("validation", new JSONObject() - .put("strict", true) - .put("fields", new JSONObject() - .put("foo", new JSONObject() - .put("mandatory", true) - .put("type", "string") - .put("defaultValue", "bar") - ) - ) - ) - ) - ); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.getSpecifications(mock(ResponseListener.class)); - collection.getSpecifications(new Options(), mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getSpecifications"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mCreateDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mCreateDocumentTest.java deleted file mode 100644 index a61ed498..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mCreateDocumentTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class mCreateDocumentTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - private Document[] documents; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - - try { - documents = new Document[]{ - new Document(collection, "foo"), - new Document(collection, "bar") - }; - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Test - public void checkMCreateDocumentSignaturesVariants() throws JSONException { - collection = spy(collection); - - collection.mCreateDocument(documents, mock(Options.class), listener); - collection.mCreateDocument(documents, listener); - collection.mCreateDocument(documents, mock(Options.class)); - collection.mCreateDocument(documents); - - verify(collection, times(4)).mCreateDocument(any(Document[].class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testMCreateDocumentQueryException() throws JSONException { - documents = new Document[]{}; - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mCreateDocument(documents, listener); - } - - @Test(expected = RuntimeException.class) - public void testMCreateDocumentException() throws JSONException { - documents = new Document[]{}; - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - collection.mCreateDocument(documents, listener); - } - - @Test - public void testMCreateDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mCreateDocument(documents, new Options(), listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "mCreate"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mCreateOrReplaceDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mCreateOrReplaceDocumentTest.java deleted file mode 100644 index 891f9198..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mCreateOrReplaceDocumentTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class mCreateOrReplaceDocumentTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - private Document[] documents; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - - try { - documents = new Document[]{ - new Document(collection, "foo"), - new Document(collection, "bar") - }; - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Test - public void checkMCreateOrReplaceDocumentSignaturesVariants() throws JSONException { - collection = spy(collection); - - collection.mCreateOrReplaceDocument(documents, mock(Options.class), listener); - collection.mCreateOrReplaceDocument(documents, listener); - collection.mCreateOrReplaceDocument(documents, mock(Options.class)); - collection.mCreateOrReplaceDocument(documents); - - verify(collection, times(4)).mCreateOrReplaceDocument(any(Document[].class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testMCreateOrReplaceDocumentQueryException() throws JSONException { - documents = new Document[]{}; - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mCreateOrReplaceDocument(documents, listener); - } - - @Test(expected = RuntimeException.class) - public void testMCreateOrReplaceDocumentException() throws JSONException { - documents = new Document[]{}; - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - collection.mCreateOrReplaceDocument(documents, listener); - } - - @Test - public void testMCreateOrReplaceDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", mock(JSONObject.class))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mCreateOrReplaceDocument(documents, new Options(), listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "mCreateOrReplace"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mDeleteDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mDeleteDocumentTest.java deleted file mode 100644 index 01663bcf..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mDeleteDocumentTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleDataCollectionExtend; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class mDeleteDocumentTest { - private Kuzzle kuzzle; - private KuzzleDataCollectionExtend collection; - private ResponseListener listener; - private String[] documentIds; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new KuzzleDataCollectionExtend(kuzzle, "index", "test"); - listener = mock(ResponseListener.class); - - documentIds = new String[]{"foo", "bar"}; - } - - @Test - public void checkMDeleteDocumentSignaturesVariants() throws JSONException { - Options opts = mock(Options.class); - collection = spy(collection); - - collection.mDeleteDocument(documentIds, opts, listener); - collection.mDeleteDocument(documentIds, listener); - collection.mDeleteDocument(documentIds, opts); - collection.mDeleteDocument(documentIds); - - verify(collection, times(4)).mDeleteDocument(any(String[].class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testMDeleteDocumentIllegalArgument() throws JSONException { - documentIds = new String[]{}; - collection.mDeleteDocument(documentIds, listener); - } - - @Test(expected = RuntimeException.class) - public void testMDeleteDocumentQueryException() throws JSONException { - documentIds = new String[]{}; - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mDeleteDocument(documentIds, listener); - } - - @Test(expected = RuntimeException.class) - public void testMDeleteDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONArray().put("_id").put("id-42"))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.mDeleteDocument(documentIds, listener); - } - - @Test - public void testMDeleteDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONArray().put("foo").put("bar"))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mDeleteDocument(documentIds, listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "mDelete"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mGetDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mGetDocumentTest.java deleted file mode 100644 index baf2c9c3..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mGetDocumentTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class mGetDocumentTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - private String[] documentIds; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - - documentIds = new String[]{"foo", "bar"}; - } - - @Test - public void checkMGetDocumentSignaturesVariants() throws JSONException { - collection = spy(collection); - - collection.mGetDocument(documentIds, mock(Options.class), listener); - collection.mGetDocument(documentIds, listener); - - verify(collection, times(2)).mGetDocument(any(String[].class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testMGetDocumentIllegalArgument() throws JSONException { - documentIds = new String[]{}; - collection.mGetDocument(documentIds, listener); - } - - @Test(expected = RuntimeException.class) - public void testMGetQueryException() throws JSONException { - documentIds = new String[]{}; - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mGetDocument(documentIds, listener); - } - - @Test(expected = RuntimeException.class) - public void testMGetDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.mGetDocument(documentIds, listener); - } - - @Test - public void testMGetDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess( - new JSONObject() - .put("result", new JSONObject() - .put("hits", new JSONArray() - .put(new JSONObject() - .put("_id", "foo") - .put("_version", 42) - .put("_source", new JSONObject()) - ) - .put(new JSONObject() - .put("_id", "bar") - .put("_version", 42) - .put("_source", new JSONObject()) - ) - ) - ) - ); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mGetDocument(documentIds, mock(ResponseListener.class)); - collection.mGetDocument(documentIds, new Options(), mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "mGet"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mReplaceDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mReplaceDocumentTest.java deleted file mode 100644 index 7d15b47b..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mReplaceDocumentTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class mReplaceDocumentTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - private Document[] documents; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - - try { - documents = new Document[]{ - new Document(collection, "foo"), - new Document(collection, "bar") - }; - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Test - public void checkMReplaceDocumentSignaturesVariants() throws JSONException { - collection = spy(collection); - - collection.mReplaceDocument(documents, mock(Options.class), listener); - collection.mReplaceDocument(documents, listener); - collection.mReplaceDocument(documents, mock(Options.class)); - collection.mReplaceDocument(documents); - - verify(collection, times(4)).mReplaceDocument(any(Document[].class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testMReplaceDocumentIllegalArgument() throws JSONException { - documents = new Document[]{}; - collection.mReplaceDocument(documents, listener); - } - - @Test(expected = RuntimeException.class) - public void testMReplaceDocumentQueryException() throws JSONException { - documents = new Document[]{}; - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mReplaceDocument(documents, mock(Options.class), listener); - } - - @Test(expected = RuntimeException.class) - public void testMReplaceDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_id", "id-42"))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.mReplaceDocument(documents, mock(Options.class), listener); - } - - @Test - public void testMReplaceDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject result = new JSONObject() - .put("result", new JSONObject() - .put("_id", "42") - .put("_version", 1337) - .put("_source", new JSONObject())); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - Document doc = new Document(collection); - doc.setContent("foo", "bar"); - collection.mReplaceDocument(documents, listener); - collection.mReplaceDocument(documents, mock(Options.class), listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "mReplace"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mUpdateDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mUpdateDocumentTest.java deleted file mode 100644 index 15c9e195..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/mUpdateDocumentTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class mUpdateDocumentTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - private Document[] documents; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - - try { - documents = new Document[]{ - new Document(collection, "foo"), - new Document(collection, "bar") - }; - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Test - public void checkMUpdateDocumentSignaturesVariants() throws JSONException { - collection = spy(collection); - - collection.mUpdateDocument(documents, mock(Options.class), listener); - collection.mUpdateDocument(documents, listener); - collection.mUpdateDocument(documents, mock(Options.class)); - collection.mUpdateDocument(documents); - - verify(collection, times(4)).mUpdateDocument(any(Document[].class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testMUpdateDocumentIllegalArgument() throws JSONException { - documents = new Document[]{}; - collection.mUpdateDocument(documents, listener); - } - - @Test(expected = RuntimeException.class) - public void testMUpdateDocumentQueryException() throws JSONException { - documents = new Document[]{}; - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.mUpdateDocument(documents, mock(Options.class), listener); - } - - @Test(expected = RuntimeException.class) - public void testMUpdateDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_id", "id-42"))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.mUpdateDocument(documents, mock(Options.class), listener); - } - - @Test - public void testMUpdateDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject result = new JSONObject() - .put("result", new JSONObject() - .put("_id", "42") - .put("_version", 1337) - .put("_source", new JSONObject())); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - Document doc = new Document(collection); - doc.setContent("foo", "bar"); - collection.mUpdateDocument(documents, listener); - collection.mUpdateDocument(documents, mock(Options.class), listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "mUpdate"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/publishMessageTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/publishMessageTest.java deleted file mode 100644 index a81187a0..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/publishMessageTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - - -public class publishMessageTest { - private Kuzzle kuzzle; - private Collection collection; - - @Mock - private ResponseListener listener; - - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - - MockitoAnnotations.initMocks(this); - } - - @Test - public void checkSignaturesVariants() { - Document doc = mock(Document.class); - - when(doc.getContent()).thenReturn(new JSONObject()); - collection = spy(collection); - - collection.publishMessage(doc); - collection.publishMessage(doc, mock(Options.class)); - collection.publishMessage(doc, listener); - collection.publishMessage(doc, mock(Options.class), listener); - collection.publishMessage(mock(JSONObject.class)); - collection.publishMessage(mock(JSONObject.class), listener); - collection.publishMessage(mock(JSONObject.class), mock(Options.class)); - collection.publishMessage(mock(JSONObject.class), mock(Options.class), listener); - verify(collection, times(8)).publishMessage(any(JSONObject.class), any(Options.class), any(ResponseListener.class)); - } - - - @Test(expected = IllegalArgumentException.class) - public void publishWithNoDocument() { - collection.publishMessage((Document) null); - } - - @Test(expected = IllegalArgumentException.class) - public void publishWithNoContent() { - collection.publishMessage((JSONObject)null); - } - - @Test(expected = RuntimeException.class) - public void testPublishMessageException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.publishMessage(mock(Document.class), mock(Options.class)); - } - - @Test - public void testPublishMessage() throws JSONException { - Document doc = new Document(collection); - doc.setContent("foo", "bar"); - collection.publishMessage(doc); - collection.publishMessage(doc, new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "realtime"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "publish"); - } - - @Test - public void testCallback() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener)invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("acknowledged", true))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - JSONObject message = new JSONObject().put("foo", "bar"); - collection.publishMessage(message, listener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "realtime"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "publish"); - } - - @Test(expected = RuntimeException.class) - public void testPublishMEssageException() { - doThrow(JSONException.class).when(kuzzle).addHeaders(any(JSONObject.class), any(JSONObject.class)); - collection.publishMessage(mock(JSONObject.class)); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/replaceDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/replaceDocumentTest.java deleted file mode 100644 index bb48df4c..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/replaceDocumentTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class replaceDocumentTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - JSONObject content = mock(JSONObject.class); - String id = "foo"; - collection = spy(collection); - - collection.replaceDocument(id, content); - collection.replaceDocument(id, content, mock(Options.class)); - collection.replaceDocument(id, content, listener); - - verify(collection, times(3)).replaceDocument(any(String.class), any(JSONObject.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testReplaceDocumentIllegalDocumentId() { - collection.replaceDocument(null, null); - } - - @Test(expected = RuntimeException.class) - public void testReplaceDocumentQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.replaceDocument("id", mock(JSONObject.class), listener); - } - - @Test(expected = RuntimeException.class) - public void testReplaceDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_id", "id-42"))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.replaceDocument("id", mock(JSONObject.class), listener); - } - - @Test - public void testReplaceDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject result = new JSONObject() - .put("result", new JSONObject() - .put("_id", "42") - .put("_version", 1337) - .put("_source", new JSONObject())); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - Document doc = new Document(collection); - doc.setContent("foo", "bar"); - collection.replaceDocument("42", doc.serialize(), listener); - collection.replaceDocument("42", mock(JSONObject.class), mock(Options.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/scrollSpecificationsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/scrollSpecificationsTest.java deleted file mode 100644 index 4ba5a5e9..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/scrollSpecificationsTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class scrollSpecificationsTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - private String scrollId; - private Options options; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - opts.setScroll("30s"); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "bar", "foo"); - listener = mock(ResponseListener.class); - scrollId = "1337"; - options = mock(Options.class); - } - - @Test - public void checkScrollSpecificationsSignaturesVariants() { - collection = spy(collection); - collection.scrollSpecifications(scrollId, listener); - verify(collection).scrollSpecifications(eq(scrollId), any(Options.class), eq(listener)); - - collection.scrollSpecifications(scrollId, options, listener); - verify(collection).scrollSpecifications(eq(scrollId), eq(options), eq(listener)); - } - - @Test(expected = IllegalArgumentException.class) - public void testScrollSpecificationsIllegalListener() { - collection.scrollSpecifications(scrollId, null); - } - - @Test(expected = RuntimeException.class) - public void testScrollSpecificationsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.scrollSpecifications(scrollId, listener); - } - - @Test(expected = RuntimeException.class) - public void testScrollSpecificationsException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(Integer.class)); - collection.scrollSpecifications(scrollId, listener); - } - - @Test - public void testScrollSpecifications() throws JSONException { - JSONObject filters = new JSONObject(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\": {\n" + - " \"hits\": [\n" + - " {\n" + - " \"_id\": \"foo#bar\",\n" + - " \"index\": \"foo\",\n" + - " \"collection\": \"bar\",\n" + - " \"_source\": {\n" + - " \"validation\": {\n" + - " \"strict\": true,\n" + - " \"fields\": {\n" + - " \"foo\": {\n" + - " \"mandatory\": true,\n" + - " \"type\": \"string\",\n" + - " \"defaultValue\": \"bar\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " },\n" + - " {\n" + - " \"_id\": \"bar#foo\",\n" + - " \"index\": \"bar\",\n" + - " \"collection\": \"foo\",\n" + - " \"_source\": {\n" + - " \"validation\": {\n" + - " \"strict\": false,\n" + - " \"fields\": {\n" + - " \"bar\": {\n" + - " \"mandatory\": true,\n" + - " \"type\": \"string\",\n" + - " \"defaultValue\": \"foo\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " ],\n" + - " \"total\": 2,\n" + - " \"scrollId\": \"1337\"\n" + - " }" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - collection.scrollSpecifications(scrollId, new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - try { - assertEquals(result.getJSONArray("hits").length(), 2); - assertEquals(result.getJSONArray("hits").getJSONObject(1).getJSONObject("_source").getJSONObject("validation").getBoolean("strict"), false); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - } - }); - collection.scrollSpecifications(scrollId, mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "scrollSpecifications"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/scrollTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/scrollTest.java deleted file mode 100644 index 174c5177..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/scrollTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.responses.SearchResult; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class scrollTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - private String scrollId; - private String scroll; - private Options options; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - scrollId = "someScrollId"; - options = mock(Options.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - collection.scroll(scrollId, listener); - verify(collection).scroll(eq(scrollId), any(Options.class), any(JSONObject.class), eq(listener)); - - collection.scroll(scrollId, options, listener); - verify(collection).scroll(eq(scrollId), eq(options), any(JSONObject.class), eq(listener)); - } - - @Test(expected = IllegalArgumentException.class) - public void testScrollIllegalListener() { - collection.scroll(scrollId, null); - } - - @Test(expected = RuntimeException.class) - public void testScrollQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.scroll(scrollId, listener); - } - - @Test(expected = RuntimeException.class) - public void testScrollException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(Integer.class)); - collection.scroll(scrollId, listener); - } - - @Test - public void testScroll() throws JSONException { - JSONObject filters = new JSONObject(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\": {\n" + - " \"_shards\": {\n" + - " \"failed\": 0,\n" + - " \"successful\": 5,\n" + - " \"total\": 5\n" + - " },\n" + - " \"hits\": [\n" + - " {\n" + - " \"_id\": \"AVJAwyDMZAGQHg9Dhfw2\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073821,\n" + - " \"lon\": 3.9130721\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"customer\"\n" + - " },\n" + - " \"_meta\": {\n" + - " \"author\": \"foo\"\n" + - " },\n" + - " \"_type\": \"users\"\n" + - " },\n" + - " {\n" + - " \"_id\": \"AVJAwyOvZAGQHg9Dhfw3\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073683,\n" + - " \"lon\": 3.8999983\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"cab\"\n" + - " },\n" + - " \"_meta\": {\n" + - " \"author\": \"foo\"\n" + - " },\n" + - " \"_type\": \"users\"\n" + - " }\n" + - " ],\n" + - " \"max_score\": 1,\n" + - " \"timed_out\": false,\n" + - " \"took\": 307,\n" + - " \"total\": 2\n" + - " }" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - collection.scroll(scrollId, new ResponseListener() { - @Override - public void onSuccess(SearchResult result) { - assertEquals(result.getTotal(), 2); - try { - assertEquals(result.getDocuments().get(1).getContent("sibling"), "none"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - } - }); - collection.scroll(scrollId, mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "scroll"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/searchSpecificationsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/searchSpecificationsTest.java deleted file mode 100644 index e5d46bf7..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/searchSpecificationsTest.java +++ /dev/null @@ -1,166 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class searchSpecificationsTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSearchSpecificationsSignaturesVariants() { - JSONObject filters = mock(JSONObject.class); - Options options = mock(Options.class); - collection = spy(collection); - - collection.searchSpecifications(listener); - collection.searchSpecifications(filters, listener); - collection.searchSpecifications(options, listener); - collection.searchSpecifications(filters, options, listener); - - verify(collection, times(4)).searchSpecifications(any(JSONObject.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testSearchSpecificationsIllegalListener() { - collection.searchSpecifications(null, null, null); - } - - @Test(expected = RuntimeException.class) - public void testSearchSpecificationsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.searchSpecifications(listener); - } - - @Test(expected = RuntimeException.class) - public void testSearchSpecificationsException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(Integer.class)); - collection.searchSpecifications(listener); - } - - @Test - public void testSearchSpecifications() throws JSONException { - JSONObject filters = new JSONObject(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\": {\n" + - " \"hits\": [\n" + - " {\n" + - " \"_id\": \"foo#bar\",\n" + - " \"index\": \"foo\",\n" + - " \"collection\": \"bar\",\n" + - " \"_source\": {\n" + - " \"validation\": {\n" + - " \"strict\": true,\n" + - " \"fields\": {\n" + - " \"foo\": {\n" + - " \"mandatory\": true,\n" + - " \"type\": \"string\",\n" + - " \"defaultValue\": \"bar\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " },\n" + - " {\n" + - " \"_id\": \"bar#foo\",\n" + - " \"index\": \"bar\",\n" + - " \"collection\": \"foo\",\n" + - " \"_source\": {\n" + - " \"validation\": {\n" + - " \"strict\": false,\n" + - " \"fields\": {\n" + - " \"bar\": {\n" + - " \"mandatory\": true,\n" + - " \"type\": \"string\",\n" + - " \"defaultValue\": \"foo\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " ],\n" + - " \"total\": 2,\n" + - " \"scrollId\": \"1337\"\n" + - " }" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - collection.searchSpecifications(filters, new ResponseListener() { - @Override - public void onSuccess(JSONObject result) { - try { - assertEquals(result.getJSONArray("hits").length(), 2); - assertEquals(result.getJSONArray("hits").getJSONObject(1).getJSONObject("_source").getJSONObject("validation").getBoolean("strict"), false); - assertEquals(result.getString("scrollId"), "1337"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - } - }); - collection.searchSpecifications(filters, mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "searchSpecifications"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/searchTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/searchTest.java deleted file mode 100644 index ed2f3871..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/searchTest.java +++ /dev/null @@ -1,279 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.SearchResult; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class searchTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - collection.search(new JSONObject(), listener); - verify(collection).search(any(JSONObject.class), any(Options.class), eq(listener)); - } - - @Test(expected = IllegalArgumentException.class) - public void testSearchIllegalListener() { - collection.search(null, null, null); - } - - @Test(expected = RuntimeException.class) - public void testSearchQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.search(null, listener); - } - - @Test(expected = RuntimeException.class) - public void testSearchException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(Integer.class)); - collection.search(null, listener); - } - - @Test - public void testSearch() throws JSONException { - JSONObject filters = new JSONObject(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\": {\n" + - " \"_shards\": {\n" + - " \"failed\": 0,\n" + - " \"successful\": 5,\n" + - " \"total\": 5\n" + - " },\n" + - " \"hits\": [\n" + - " {\n" + - " \"_id\": \"AVJAwyDMZAGQHg9Dhfw2\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073821,\n" + - " \"lon\": 3.9130721\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"customer\"\n" + - " },\n" + - " \"_meta\": {\n" + - " \"author\": \"foo\"\n" + - " },\n" + - " \"_type\": \"users\"\n" + - " },\n" + - " {\n" + - " \"_id\": \"AVJAwyOvZAGQHg9Dhfw3\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073683,\n" + - " \"lon\": 3.8999983\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"cab\"\n" + - " },\n" + - " \"_meta\": {\n" + - " \"author\": \"foo\"\n" + - " },\n" + - " \"_type\": \"users\"\n" + - " }\n" + - " ],\n" + - " \"max_score\": 1,\n" + - " \"timed_out\": false,\n" + - " \"took\": 307,\n" + - " \"total\": 2\n" + - " }" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - collection.search(filters, new ResponseListener() { - @Override - public void onSuccess(SearchResult result) { - assertEquals(result.getTotal(), 2); - try { - assertEquals(result.getDocuments().get(1).getContent("sibling"), "none"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - } - }); - collection.search(filters, mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "search"); - } - - @Test - public void testSearchWithAggregations() throws JSONException { - JSONObject filters = new JSONObject(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\": {\n" + - " \"_shards\": {\n" + - " \"failed\": 0,\n" + - " \"successful\": 5,\n" + - " \"total\": 5\n" + - " },\n" + - " \"hits\": [\n" + - " {\n" + - " \"_id\": \"AVJAwyDMZAGQHg9Dhfw2\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073821,\n" + - " \"lon\": 3.9130721\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"customer\"\n" + - " },\n" + - " \"_meta\": {\n" + - " \"author\": \"foo\"\n" + - " },\n" + - " \"_type\": \"users\"\n" + - " },\n" + - " {\n" + - " \"_id\": \"AVJAwyOvZAGQHg9Dhfw3\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073683,\n" + - " \"lon\": 3.8999983\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"cab\"\n" + - " },\n" + - " \"_meta\": {\n" + - " \"author\": \"foo\"\n" + - " },\n" + - " \"_type\": \"users\"\n" + - " }\n" + - " ],\n" + - " \"aggregations\": {\n" + - " \"aggs_name\": {\n" + - " \"buckets\": [\n" + - " {\n" + - " \"doc_count\": 5,\n" + - " \"key\": \"i\"\n" + - " },\n" + - " {\n" + - " \"doc_count\": 2,\n" + - " \"key\": \"hate\"\n" + - " },\n" + - " {\n" + - " \"doc_count\": 1,\n" + - " \"key\": \"admir\"\n" + - " }\n" + - " ],\n" + - " \"doc_count_error_upper_bound\": 0,\n" + - " \"sum_other_doc_count\": 1\n" + - " }\n" + - " },\n" + - " \"max_score\": 1,\n" + - " \"timed_out\": false,\n" + - " \"took\": 307,\n" + - " \"total\": 2\n" + - " }" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - collection.search(filters, new ResponseListener() { - @Override - public void onSuccess(SearchResult result) { - assertEquals(result.getTotal(), 2); - try { - assertEquals(result.getAggregations().getJSONObject("aggs_name").getJSONArray("buckets").getJSONObject(0).getString("key"), "i"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - try { - assertEquals(result.getDocuments().get(1).getContent("sibling"), "none"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - } - }); - collection.search(filters, mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "search"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/subscribeTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/subscribeTest.java deleted file mode 100644 index 05a28ac2..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/subscribeTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.RoomOptions; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class subscribeTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - collection.subscribe(new JSONObject(), listener); - verify(collection).subscribe(any(JSONObject.class), eq((RoomOptions)null), eq(listener)); - } - - - @Test(expected = IllegalArgumentException.class) - public void testSubscribeIllegalListener() { - collection.subscribe(mock(JSONObject.class), null); - } - - @Test - public void testSubscribe() throws JSONException { - final ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - //Mock response - JSONObject result = new JSONObject(); - result.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - //Call callback with response - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - verify(kuzzle, atLeastOnce()).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "realtime"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "subscribe"); - - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.subscribe(mock(JSONObject.class), new RoomOptions(), listener); - collection.subscribe(mock(JSONObject.class), listener); - collection.subscribe(new RoomOptions(), listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/truncateTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/truncateTest.java deleted file mode 100644 index 5804fd8c..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/truncateTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class truncateTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - collection = spy(collection); - collection.truncate(); - collection.truncate(mock(Options.class)); - collection.truncate(listener); - verify(collection, times(3)).truncate(any(Options.class), any(ResponseListener.class)); - } - - - @Test(expected = RuntimeException.class) - public void testTruncateQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.truncate(listener); - } - - @Test(expected = RuntimeException.class) - public void testTruncateException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.truncate(listener); - } - - @Test - public void testTruncate() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.truncate(); - collection.truncate(new Options()); - collection.truncate(mock(ResponseListener.class)); - collection.truncate(new Options(), mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(4)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "truncate"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/updateDocumentTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/updateDocumentTest.java deleted file mode 100644 index dafc8938..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/updateDocumentTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.KuzzleJSONObject; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class updateDocumentTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkSignaturesVariants() { - JSONObject content = mock(JSONObject.class); - String id = "foo"; - collection = spy(collection); - - collection.updateDocument(id, content); - collection.updateDocument(id, content, mock(Options.class)); - collection.updateDocument(id, content, listener); - - verify(collection, times(3)).updateDocument(any(String.class), any(JSONObject.class), any(Options.class), any(ResponseListener.class)); - } - - - @Test(expected = IllegalArgumentException.class) - public void testUpdateDocumentIllegalDocumentId() { - collection.updateDocument(null, mock(JSONObject.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testUpdateDocumentIllegalContent() { - collection.updateDocument("id", null); - } - - @Test(expected = RuntimeException.class) - public void testupdateDocumentQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.updateDocument("id", mock(JSONObject.class), listener); - } - - @Test(expected = RuntimeException.class) - public void testupdateDocumentException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(String.class)); - collection.updateDocument("id", mock(JSONObject.class), listener); - } - - @Test - public void testUpdateDocument() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject() - .put("result", new JSONObject() - .put("_id", "42") - .put("_version", 1337) - .put("_source", new JSONObject()) - .put("_meta", new JSONObject()) - ); - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - } - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - Document doc = new Document(collection); - collection.updateDocument("42", doc.serialize()); - collection.updateDocument("42", doc.serialize(), new Options()); - collection.updateDocument("42", doc.serialize(), new ResponseListener() { - @Override - public void onSuccess(Document document) { - assertEquals(document.getId(), "42"); - assertEquals(document.getVersion(), 1337); - } - - @Override - public void onError(JSONObject error) { - - } - }); - collection.updateDocument("42", doc.serialize(), new Options(), new ResponseListener() { - @Override - public void onSuccess(Document document) { - assertEquals(document.getId(), "42"); - } - - @Override - public void onError(JSONObject error) { - - } - }); - verify(kuzzle, times(6)).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } - - @Test - public void testRetryOnConflict() throws JSONException { - Options opts = new Options().setRetryOnConflict(42); - Document doc = new Document(collection); - ArgumentCaptor capturedQuery = ArgumentCaptor.forClass(KuzzleJSONObject.class); - - collection.updateDocument("foo", doc.serialize(), opts); - verify(kuzzle).query(any(Kuzzle.QueryArgs.class), (JSONObject)capturedQuery.capture(), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((JSONObject)capturedQuery.getValue()).getInt("retryOnConflict"), 42); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/updateSpecificationsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/updateSpecificationsTest.java deleted file mode 100644 index b550d4ec..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/updateSpecificationsTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class updateSpecificationsTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkUpdateSpecificationsSignaturesVariants() throws JSONException { - JSONObject content = mock(JSONObject.class); - collection = spy(collection); - - collection.updateSpecifications(content); - collection.updateSpecifications(content, mock(Options.class)); - collection.updateSpecifications(content, listener); - collection.updateSpecifications(content, mock(Options.class), listener); - - verify(collection, times(4)).updateSpecifications(any(JSONObject.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testUpdateSpecificationsIllegalArgument() throws JSONException { - collection.updateSpecifications(null); - } - - @Test(expected = RuntimeException.class) - public void testUpdateSpecificationsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.updateSpecifications(mock(JSONObject.class), listener); - } - - @Test(expected = RuntimeException.class) - public void testUpdateSpecificationsException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - collection.updateSpecifications(mock(JSONObject.class), listener); - } - - @Test - public void testUpdateSpecifications() throws JSONException { - final JSONObject specifications = new JSONObject() - .put("index", new JSONObject() - .put("test", new JSONObject() - .put("strict", true) - .put("fields", new JSONObject() - .put("foo", new JSONObject() - .put("mandatory", true) - .put("type", "string") - .put("defaultValue", "bar") - ) - ) - ) - ); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject() - .put("result", specifications); - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - } - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - collection.updateSpecifications(new JSONObject()); - collection.updateSpecifications(new JSONObject(), new Options()); - collection.updateSpecifications(new JSONObject(), new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - assertEquals(response, specifications); - assertEquals(response, specifications); - } - - @Override - public void onError(JSONObject error) { - - } - }); - collection.updateSpecifications(new JSONObject(), new Options(), new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - assertEquals(response, specifications); - } - - @Override - public void onError(JSONObject error) { - - } - }); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(4)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "updateSpecifications"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/validateSpecificationsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/validateSpecificationsTest.java deleted file mode 100644 index 2de8fba6..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataCollection/validateSpecificationsTest.java +++ /dev/null @@ -1,146 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataCollection; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class validateSpecificationsTest { - private Kuzzle kuzzle; - private Collection collection; - private ResponseListener listener; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - } - - @Test - public void checkValidateSpecificationsSignaturesVariants() throws JSONException { - JSONObject specifications = mock(JSONObject.class); - collection = spy(collection); - - collection.validateSpecifications(specifications, listener); - collection.validateSpecifications(specifications, mock(Options.class), listener); - - verify(collection, times(2)).validateSpecifications(any(JSONObject.class), any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testValidateSpecificationsIllegalArgument() throws JSONException { - collection.validateSpecifications(null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testValidateSpecificationsIllegalListener() throws JSONException { - collection.validateSpecifications(null, null); - } - - @Test(expected = RuntimeException.class) - public void testValidateSpecificationsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - collection.validateSpecifications(mock(JSONObject.class), listener); - } - - @Test(expected = RuntimeException.class) - public void testValidateSpecificationsException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("valid", true))); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - collection.validateSpecifications(mock(JSONObject.class), listener); - } - - @Test - public void testValidateSpecifications() throws JSONException { - final JSONObject validateSpecificationsResponse = new JSONObject().put("valid", true); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject() - .put("result", validateSpecificationsResponse); - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - } - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - collection.validateSpecifications(new JSONObject(), new ResponseListener() { - @Override - public void onSuccess(Boolean isValid) { - try { - assertEquals(isValid, validateSpecificationsResponse.getBoolean("valid")); - assertEquals(isValid, validateSpecificationsResponse.getBoolean("valid")); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Override - public void onError(JSONObject error) { - - } - }); - collection.validateSpecifications(new JSONObject(), new Options(), new ResponseListener() { - @Override - public void onSuccess(Boolean isValid) { - try { - assertEquals(isValid, validateSpecificationsResponse.getBoolean("valid")); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Override - public void onError(JSONObject error) { - - } - }); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "validateSpecifications"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/applyTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/applyTest.java deleted file mode 100644 index d83d1118..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/applyTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataMapping; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.CollectionMapping; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class applyTest { - private Kuzzle k; - private Collection dataCollection; - private CollectionMapping dataMapping; - - @Before - public void setUp() { - k = mock(Kuzzle.class); - when(k.getDefaultIndex()).thenReturn("index"); - when(k.getHeaders()).thenReturn(new JSONObject()); - dataCollection = new Collection(k, "test", "index"); - dataMapping = new CollectionMapping(dataCollection); - } - - @Test - public void checkSignaturesVariants() { - dataMapping = spy(dataMapping); - dataMapping.apply(); - dataMapping.apply(mock(Options.class)); - dataMapping.apply(mock(ResponseListener.class)); - verify(dataMapping, times(3)).apply(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testApplyQueryException() throws JSONException { - doThrow(JSONException.class).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - dataMapping.apply(); - } - - @Test(expected = RuntimeException.class) - public void testApplyException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - ResponseListener mockListener = mock(ResponseListener.class); - doThrow(JSONException.class).when(mockListener).onSuccess(any(CollectionMapping.class)); - dataMapping.apply(mockListener); - } - - @Test - public void testApply() throws JSONException { - final JSONObject mockResponse = new JSONObject("{\n" + - " properties: {\n" + - " field1: {type: \"field type\"},\n" + - " field2: {type: \"field type\"},\n" + - " fieldn: {type: \"field type\"}\n" + - " }\n" + - " }"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mockResponse); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(null); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - dataMapping.apply(); - dataMapping.apply(new Options()); - dataMapping.apply(mock(ResponseListener.class)); - dataMapping.apply(new Options(), mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(k, times(4)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "updateMapping"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/constructorTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/constructorTest.java deleted file mode 100644 index 139fb5f8..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/constructorTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataMapping; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.CollectionMapping; - -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.hamcrest.junit.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -public class constructorTest { - private Kuzzle k; - private Collection dataCollection; - private CollectionMapping dataMapping; - - @Before - public void setUp() { - k = mock(Kuzzle.class); - when(k.getDefaultIndex()).thenReturn("index"); - when(k.getHeaders()).thenReturn(new JSONObject()); - dataCollection = new Collection(k, "test", "index"); - dataMapping = new CollectionMapping(dataCollection); - } - - @Test(expected = RuntimeException.class) - public void testConstructorException() { - Collection fake = spy(new Collection(k, "test", "index")); - doThrow(JSONException.class).when(fake).getHeaders(); - dataMapping = new CollectionMapping(fake); - } - - @Test - public void testConstructor() throws JSONException { - JSONObject mapping = new JSONObject(); - mapping.put("type", "string"); - dataMapping = new CollectionMapping(dataCollection, mapping); - dataMapping = new CollectionMapping(dataMapping); - } - - @Test - public void testSetHeaders() throws JSONException { - dataMapping.setHeaders(null, true); - JSONObject headers = new JSONObject(); - headers.put("foo", "bar"); - dataMapping.setHeaders(headers, true); - assertEquals(dataMapping.getHeaders().getString("foo"), "bar"); - headers.put("oof", "baz"); - dataMapping.setHeaders(headers); - assertEquals(dataMapping.getHeaders().getString("foo"), "bar"); - assertEquals(dataMapping.getHeaders().getString("oof"), "baz"); - } - - @Test(expected = RuntimeException.class) - public void testSetHeadersException() { - JSONObject json = spy(new JSONObject()); - doThrow(JSONException.class).when(json).keys(); - dataMapping.setHeaders(json, false); - } - - @Test - public void testGetHeaders() throws JSONException { - dataMapping.setHeaders(null); - assertNotNull(dataMapping.getHeaders()); - JSONObject headers = new JSONObject(); - headers.put("foo", "bar"); - dataMapping.setHeaders(headers); - assertEquals(dataMapping.getHeaders().getString("foo"), "bar"); - } - - @Test - public void testSet() throws JSONException { - JSONObject mapping = mock(JSONObject.class); - assertThat(dataMapping.set("foo", mapping), instanceOf(CollectionMapping.class)); - assertEquals(dataMapping.getMapping().getJSONObject("foo"), mapping); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/refreshTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/refreshTest.java deleted file mode 100644 index 8bf8485b..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/refreshTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataMapping; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.CollectionMapping; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class refreshTest { - private Kuzzle k; - private Collection dataCollection; - private CollectionMapping dataMapping; - - @Before - public void setUp() { - k = mock(Kuzzle.class); - when(k.getDefaultIndex()).thenReturn("index"); - when(k.getHeaders()).thenReturn(new JSONObject()); - dataCollection = new Collection(k, "test", "index"); - dataMapping = new CollectionMapping(dataCollection); - } - - @Test - public void checkSignaturesVariants() { - dataMapping = spy(dataMapping); - dataMapping.refresh(mock(ResponseListener.class)); - verify(dataMapping).refresh(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testRefreshIllegalListener() { - dataMapping.refresh(null); - } - - @Test(expected = RuntimeException.class) - public void testException() throws JSONException { - doThrow(JSONException.class).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - dataMapping.refresh(mock(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testRefreshException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject("{\"index\": {\n" + - " \"mappings\": {\n" + - " \"users\": {\n" + - " \"properties\": {\n" + - " \"pos\": {\n" + - " \"type\": \"geo_point\"\n" + - " },\n" + - " \"sibling\": {\n" + - " \"type\": \"string\"\n" + - " },\n" + - " \"status\": {\n" + - " \"type\": \"string\"\n" + - " },\n" + - " \"type\": {\n" + - " \"type\": \"string\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }" + - "}")); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - ResponseListener mockListener = mock(ResponseListener.class); - doThrow(JSONException.class).when(mockListener).onSuccess(any(CollectionMapping.class)); - dataMapping.refresh(mockListener); - } - - @Test - public void testRefresh() throws JSONException { - final JSONObject mockMapping = new JSONObject("{\"index\": {\"mappings\": {" + - " \"test\": {" + - " \"properties\": {" + - " \"available\": {" + - " \"type\": \"boolean\"" + - " }," + - " \"foo\": {" + - " \"type\": \"string\"" + - " }," + - " \"type\": {" + - " \"type\": \"string\"" + - " }," + - " \"userId\": {" + - " \"type\": \"string\"" + - " }" + - " }" + - " }}}}"); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = mockMapping; - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(null); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - when(k.getDefaultIndex()).thenReturn("index"); - - dataMapping.refresh(new ResponseListener() { - @Override - public void onSuccess(CollectionMapping response) { - assertNotEquals(dataMapping, response); - try { - assertEquals( - mockMapping.getJSONObject("index").getJSONObject("mappings").getJSONObject("test"), - response.getMapping() - ); - } - catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onError(JSONObject error) { - - } - }); - dataMapping.refresh(new Options(), mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(k, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "collection"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getMapping"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/removeTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/removeTest.java deleted file mode 100644 index e491394b..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDataMapping/removeTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDataMapping; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import io.kuzzle.sdk.core.CollectionMapping; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class removeTest { - private Kuzzle k; - private Collection dataCollection; - private CollectionMapping dataMapping; - - @Before - public void setUp() { - k = mock(Kuzzle.class); - when(k.getDefaultIndex()).thenReturn("index"); - when(k.getHeaders()).thenReturn(new JSONObject()); - dataCollection = new Collection(k, "test", "index"); - dataMapping = new CollectionMapping(dataCollection); - } - - @Test - public void testRemove() throws JSONException { - JSONObject mapping = new JSONObject(); - mapping.put("type", "string"); - dataMapping.set("foo", mapping); - assertEquals(dataMapping.getMapping().getJSONObject("foo").getString("type"), "string"); - dataMapping.remove("foo"); - assertTrue(dataMapping.getMapping().isNull("foo")); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/constructorTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/constructorTest.java deleted file mode 100644 index de64bdd2..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/constructorTest.java +++ /dev/null @@ -1,178 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDocument; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class constructorTest { - private Kuzzle k; - private Document doc; - - @Before - public void setUp() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setState(States.CONNECTED); - k = spy(extended); - doc = new Document(new Collection(k, "test", "index")); - } - - @Test(expected = IllegalArgumentException.class) - public void testConstructorIllegalDataCollection() throws JSONException { - new Document(null, null, null, null); - } - - @Test - public void testConstructor() throws JSONException { - doc = new Document(new Collection(k, "test", "index"), "42"); - assertEquals(doc.getId(), "42"); - } - - @Test - public void testCollection() throws JSONException { - Kuzzle k = mock(Kuzzle.class); - when(k.getHeaders()).thenReturn(new JSONObject()); - Collection collection = new Collection(k, "test", "index"); - Document doc = new Document(collection); - assertEquals(doc.getCollection(), collection.getCollection()); - } - - @Test - public void testDocumentWithContent() throws JSONException { - JSONObject content = new JSONObject(); - content.put("foo", "bar"); - - doc = new Document(new Collection(k, "test", "index"), content); - assertEquals(doc.getContent().getString("foo"), "bar"); - } - - @Test(expected = RuntimeException.class) - public void testSetContentPutException() throws JSONException { - doc = spy(doc); - doc.setContent(mock(JSONObject.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetContentIllegalKey() throws JSONException { - doc.setContent(null, "value"); - } - - @Test - public void testSetContentUpdateVersion() throws JSONException { - JSONObject content = new JSONObject() - .put("version", 42424242); - doc.setContent(content, false); - assertEquals(42424242, doc.getVersion()); - } - - @Test - public void checkSetContentVariants() throws JSONException { - doc = spy(doc); - doc.setContent(new JSONObject()); - verify(doc).setContent(any(JSONObject.class), eq(false)); - } - - @Test - public void testSetContent() throws JSONException { - assertEquals(doc.getContent().toString(), new JSONObject().toString()); - JSONObject data = new JSONObject(); - data.put("test", "some content"); - doc.setContent(data, false); - assertEquals(doc.getContent().get("test"), "some content"); - data = new JSONObject(); - data.put("test 2", "some other content"); - doc.setContent(data, true); - assertEquals(doc.getContent().get("test 2"), "some other content"); - assertTrue(doc.getContent().isNull("test")); - } - - @Test - public void testGetContent() throws JSONException { - doc.setContent(null); - assertNotNull(doc.getContent()); - doc.setContent("foo", "bar"); - assertEquals(doc.getContent().getString("foo"), "bar"); - assertNull(doc.getContent("!exist")); - } - - @Test - public void testDocumentWithMetadata() throws JSONException { - JSONObject content = new JSONObject(); - content.put("foo", "bar"); - - JSONObject meta = new JSONObject(); - meta.put("author", "foo"); - - doc = new Document(new Collection(k, "test", "index"), content, meta); - assertEquals(doc.getMeta().getString("author"), "foo"); - } - - @Test - public void checkSetHeadersVariants() { - doc = spy(doc); - doc.setHeaders(new JSONObject()); - verify(doc).setHeaders(any(JSONObject.class), eq(false)); - } - - @Test(expected = RuntimeException.class) - public void testSetHeadersException() { - JSONObject fake = spy(new JSONObject()); - doThrow(JSONException.class).when(fake).toString(); - doc.setHeaders(fake, true); - } - - @Test - public void testSetHeaders() throws JSONException { - doc.setHeaders(null, true); - assertNotNull(doc.getHeaders()); - JSONObject headers = new JSONObject(); - headers.put("foo", "bar"); - doc.setHeaders(headers, true); - assertEquals(doc.getHeaders().getString("foo"), "bar"); - headers.put("oof", "baz"); - doc.setHeaders(headers); - assertEquals(doc.getHeaders().getString("foo"), "bar"); - assertEquals(doc.getHeaders().getString("oof"), "baz"); - } - - @Test - public void testGetHeaders() throws JSONException { - doc.setHeaders(null); - assertNotNull(doc.getHeaders()); - JSONObject headers = new JSONObject(); - headers.put("foo", "bar"); - doc.setHeaders(headers); - assertEquals(doc.getHeaders().getString("foo"), "bar"); - } - - @Test - public void testGetVersion() throws JSONException { - assertEquals(-1, doc.getVersion()); - doc.setVersion(42); - assertEquals(42, doc.getVersion()); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/deleteTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/deleteTest.java deleted file mode 100644 index c2538496..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/deleteTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDocument; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class deleteTest { - private Kuzzle k; - private Document doc; - - @Before - public void setUp() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setState(States.CONNECTED); - extended.setSocket(mock(WebSocketClient.class)); - k = spy(extended); - doc = new Document(new Collection(k, "test", "index")); - } - - @Test - public void checkSignaturesVariants() { - doc.setId("foo"); - doc = spy(doc); - doc.delete(); - doc.delete(mock(Options.class)); - doc.delete(mock(ResponseListener.class)); - verify(doc, times(3)).delete(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = IllegalStateException.class) - public void cannotDeleteWithoutID() { - doc.delete(); - } - - @Test(expected = RuntimeException.class) - public void testDeleteException() throws JSONException { - doc.setId("42"); - doThrow(JSONException.class).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.delete(); - } - - @Test - public void testDelete() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - response.put("result", "foo"); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(null); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.setId("id-42"); - doc.delete(mock(ResponseListener.class)); - doc.setId("id-42"); - doc.delete(); - doc.setId("id-42"); - doc.delete(mock(Options.class)); - assertNull(doc.getId()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(k, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "delete"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/existsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/existsTest.java deleted file mode 100644 index 634f86bd..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/existsTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDocument; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class existsTest { - private Kuzzle k; - private Document doc; - private ResponseListener mockListener; - - @Before - public void setUp() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setState(States.CONNECTED); - extended.setSocket(mock(WebSocketClient.class)); - k = spy(extended); - mockListener = mock(ResponseListener.class); - doc = new Document(new Collection(k, "test", "index")); - } - - @Test - public void checkSignaturesVariants() { - doc.setId("foo"); - doc = spy(doc); - doc.exists(mockListener); - verify(doc).exists(eq((Options)null), eq(mockListener)); - } - - @Test(expected = IllegalArgumentException.class) - public void testExistsNullListenerException() throws IllegalArgumentException { - doc.setId("42"); - doc.exists(null); - } - - @Test(expected = RuntimeException.class) - public void testExistsQueryException() throws JSONException { - doc.setId("42"); - doThrow(JSONException.class).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.exists(mockListener); - } - - @Test(expected = RuntimeException.class) - public void testExistsException() throws JSONException { - doc.setId("42"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject result = new JSONObject() - .put("result", true); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(mockListener).onSuccess(any(JSONObject.class)); - doc.exists(mockListener); - } - - @Test(expected = IllegalStateException.class) - public void testExistsWithoutId() { - doc.exists(null, null); - } - - @Test - public void testExists() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject() - .put("result", true); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(null); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.setId("42"); - doc.setContent("foo", "baz"); - doc.exists(new ResponseListener() { - @Override - public void onSuccess(Boolean exists) { - assertEquals(exists, true); - } - - @Override - public void onError(JSONObject error) { - - } - }); - doc.exists(mockListener); - doc.exists(mock(Options.class), mockListener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(k, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "exists"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/publishTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/publishTest.java deleted file mode 100644 index 9c9613b5..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/publishTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDocument; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class publishTest { - private Kuzzle k; - private Document doc; - - @Before - public void setUp() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setState(States.CONNECTED); - extended.setSocket(mock(WebSocketClient.class)); - k = spy(extended); - doc = new Document(new Collection(k, "test", "index")); - } - - @Test - public void checkSignaturesVariants() { - doc = spy(doc); - doc.publish(); - verify(doc).publish(eq((Options)null)); - } - - @Test(expected = RuntimeException.class) - public void testPublishException() throws JSONException { - doThrow(JSONException.class).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.publish(); - } - - @Test - public void testPublish() throws JSONException { - doc.publish(); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(k, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "realtime"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "publish"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/refreshTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/refreshTest.java deleted file mode 100644 index de89ab5b..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/refreshTest.java +++ /dev/null @@ -1,140 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDocument; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class refreshTest { - private Kuzzle k; - private Document doc; - private ResponseListener mockListener; - - @Before - public void setUp() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setState(States.CONNECTED); - extended.setSocket(mock(WebSocketClient.class)); - k = spy(extended); - mockListener = mock(ResponseListener.class); - doc = new Document(new Collection(k, "test", "index")); - } - - @Test - public void checkSignaturesVariants() { - doc.setId("foo"); - doc = spy(doc); - doc.refresh(mockListener); - verify(doc).refresh(eq((Options)null), eq(mockListener)); - } - - @Test(expected = IllegalArgumentException.class) - public void testRefreshNullListenerException() throws IllegalArgumentException { - doc.setId("42"); - doc.refresh(null); - } - - @Test(expected = RuntimeException.class) - public void testRefreshQueryException() throws JSONException { - doc.setId("42"); - doThrow(JSONException.class).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.refresh(mockListener); - } - - @Test(expected = RuntimeException.class) - public void testRefreshException() throws JSONException { - doc.setId("42"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject result = new JSONObject() - .put("result", new JSONObject() - .put("_id", "foo") - .put("_source", mock(JSONObject.class)) - ); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(mockListener).onSuccess(any(Document.class)); - doc.refresh(mockListener); - } - - @Test(expected = IllegalStateException.class) - public void testRefreshWithoutId() { - doc.refresh(null, null); - } - - @Test - public void testRefresh() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject() - .put("result", new JSONObject() - .put("_id", "42") - .put("_version", 1337) - .put("_source", new JSONObject().put("foo", "bar")) - .put("_meta", new JSONObject().put("author", "foo"))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(null); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.setId("42"); - doc.setContent("foo", "baz"); - doc.refresh(new ResponseListener() { - @Override - public void onSuccess(Document object) { - try { - assertEquals(1337, object.getVersion()); - assertEquals("bar", object.getContent().getString("foo")); - assertNotEquals(doc, object); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Override - public void onError(JSONObject error) { - - } - }); - doc.refresh(mockListener); - doc.refresh(mock(Options.class), mockListener); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(k, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "get"); - - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/saveTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/saveTest.java deleted file mode 100644 index 87eed549..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/saveTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDocument; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class saveTest { - private Kuzzle k; - private Document doc; - private ResponseListener mockListener; - - @Before - public void setUp() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setState(States.CONNECTED); - extended.setSocket(mock(WebSocketClient.class)); - k = spy(extended); - mockListener = mock(ResponseListener.class); - doc = new Document(new Collection(k, "test", "index")); - } - - @Test - public void checkSignaturesVariants() { - doc = spy(doc); - doc.save(); - doc.save(mock(Options.class)); - doc.save(mockListener); - verify(doc, times(3)).save(any(Options.class), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testSaveQueryException() throws JSONException { - doc.setId("42"); - doThrow(JSONException.class).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.save(); - } - - @Test(expected = RuntimeException.class) - public void testSaveException() throws JSONException { - doc.setId("42"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("_id", "42").put("_version", "42"))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(mockListener).onSuccess(any(Document.class)); - doc.save(mockListener); - } - - @Test - public void testSave() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - response.put("_id", "id-42"); - response.put("_version", "42"); - response.put("result", response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(null); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.save(); - doc.save(new Options()); - doc.save(new ResponseListener() { - @Override - public void onSuccess(Document object) { - assertEquals(object.getId(), "id-42"); - } - - @Override - public void onError(JSONObject error) { - - } - }); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(k, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createOrReplace"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/serializeTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/serializeTest.java deleted file mode 100644 index c0369023..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/serializeTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDocument; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.spy; - -public class serializeTest { - - private Kuzzle k; - private Document doc; - - @Before - public void setUp() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setState(States.CONNECTED); - k = spy(extended); - doc = new Document(new Collection(k, "test", "index")); - } - - @Test(expected = RuntimeException.class) - public void testException() { - doThrow(JSONException.class).when(k).addHeaders(any(JSONObject.class), any(JSONObject.class)); - doc.serialize(); - } - - @Test - public void testToString() throws JSONException { - JSONObject o = new JSONObject() - .put("foo", "bar"); - doc.setId("42"); - doc.setVersion(4242); - doc.setContent(o); - assertEquals(doc.toString(), "{\"_id\":\"42\",\"body\":{\"foo\":\"bar\"},\"_version\":4242}"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/subscribeTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/subscribeTest.java deleted file mode 100644 index 993a4496..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleDocument/subscribeTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleDocument; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.RoomOptions; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -public class subscribeTest { - private Kuzzle k; - private Document doc; - private Collection mockCollection; - - @Before - public void setUp() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setState(States.CONNECTED); - extended.setSocket(mock(WebSocketClient.class)); - k = spy(extended); - mockCollection = mock(Collection.class); - doc = new Document(new Collection(k, "test", "index")); - } - - @Test - public void checkSignaturesVariants() { - doc.setId("foo"); - doc = spy(doc); - doc.subscribe(mock(ResponseListener.class)); - verify(doc).subscribe(eq((RoomOptions)null), any(ResponseListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testSubscribeException() throws JSONException { - doc = new Document(mockCollection); - doc.setId("42"); - doThrow(JSONException.class).when(mockCollection).subscribe(any(JSONObject.class), any(RoomOptions.class), any(ResponseListener.class)); - doc.subscribe(mock(ResponseListener.class)); - } - - @Test(expected = IllegalStateException.class) - public void testSubscribeNullId() { - doc.subscribe(mock(ResponseListener.class)); - } - - @Test - public void testSubscribe() throws JSONException { - final ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - //Mock response - JSONObject result = new JSONObject(); - result.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - //Call callback with response - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - verify(k, atLeastOnce()).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "realtime"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "subscribe"); - - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doc.setId("42"); - doc.subscribe(mock(ResponseListener.class)); - doc.subscribe(new RoomOptions(), mock(ResponseListener.class)); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleMemoryStorage/methodsTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleMemoryStorage/methodsTest.java deleted file mode 100644 index 84d9433b..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleMemoryStorage/methodsTest.java +++ /dev/null @@ -1,2458 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleMemoryStorage; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.skyscreamer.jsonassert.JSONAssert; - -import java.lang.reflect.Method; -import java.util.Arrays; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.MemoryStorage; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.util.KuzzleJSONObject; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class methodsTest { - private Kuzzle kuzzle; - private Kuzzle.QueryArgs queryArgs = new Kuzzle.QueryArgs(); - private MemoryStorage ms; - private ArgumentCaptor capturedQueryArgs; - private ArgumentCaptor capturedQuery; - - private static T[] concat(T[] first, T[] second) { - T[] result = Arrays.copyOf(first, first.length + second.length); - System.arraycopy(second, 0, result, first.length, second.length); - return result; - } - - private void validate(String command, JSONObject expected, boolean withOpts) throws JSONException { - assertEquals(((Kuzzle.QueryArgs) capturedQueryArgs.getValue()).controller, "ms"); - assertEquals(((Kuzzle.QueryArgs) capturedQueryArgs.getValue()).action, command); - - /* - if options are provided, the expected result should come first - as the assertion expects the second argument to contain at least - the JSON properties contained in the first one - - And vice versa without options provided - */ - if (withOpts) { - JSONAssert.assertEquals(expected, (JSONObject)capturedQuery.getValue(), false); - } - else { - JSONAssert.assertEquals(capturedQuery.getValue().toString(), expected, false); - } - } - - private ResponseListener verifyResultLong(long returnValue, final long expected) throws JSONException { - mockResult(new KuzzleJSONObject().put("result", returnValue)); - - return new ResponseListener() { - @Override - public void onSuccess(Long response) { - assertEquals((long)response, expected); - } - - @Override - public void onError(JSONObject error) { - } - }; - } - - private ResponseListener verifyResultInt(int returnValue, final int expected) throws JSONException { - mockResult(new KuzzleJSONObject().put("result", returnValue)); - - return new ResponseListener() { - @Override - public void onSuccess(Integer response) { - assertEquals((int)response, expected); - } - - @Override - public void onError(JSONObject error) { - } - }; - } - - private ResponseListener verifyResultString(String returnValue, final String expected) throws JSONException { - mockResult(new KuzzleJSONObject().put("result", returnValue)); - - return new ResponseListener() { - @Override - public void onSuccess(String response) { - assertEquals(response, expected); - } - - @Override - public void onError(JSONObject error) { - } - }; - } - - private ResponseListener verifyResultStringArray(String returnValue, final String[] expected) throws JSONException { - mockResult(new KuzzleJSONObject().put("result", returnValue)); - - return new ResponseListener() { - @Override - public void onSuccess(String[] response) { - assertArrayEquals(response, expected); - } - - @Override - public void onError(JSONObject error) { - } - }; - } - - private ResponseListener verifyResultStringArray(final JSONArray returnValue, final String[] expected) throws JSONException { - mockResult(new KuzzleJSONObject().put("result", returnValue)); - - return new ResponseListener() { - @Override - public void onSuccess(String[] response) { - assertArrayEquals(response, expected); - } - - @Override - public void onError(JSONObject error) { - } - }; - } - - private ResponseListener verifyResultJSONObjectArray(JSONArray value, final JSONObject[] expected) throws JSONException { - mockResult(new KuzzleJSONObject().put("result", value)); - - return new ResponseListener() { - @Override - public void onSuccess(JSONObject[] response) { - for (int i = 0; i < response.length; i++) { - try { - JSONAssert.assertEquals(response[i], expected[i], false); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - private ResponseListener verifyResultDouble(String returnValue, final double expected) throws JSONException { - mockResult(new KuzzleJSONObject().put("result", returnValue)); - - return new ResponseListener() { - @Override - public void onSuccess(Double response) { - assertEquals(response, expected, 10e-12); - } - - @Override - public void onError(JSONObject error) { - } - }; - } - - private ResponseListener verifyResultJSONObject(JSONArray value, final JSONObject expected) throws JSONException { - mockResult(new KuzzleJSONObject().put("result", value)); - - return new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - try { - JSONAssert.assertEquals(response, expected, false); - } - catch(JSONException e) { - fail(e.getMessage()); - } - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - private void mockResult(final KuzzleJSONObject raw) throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(raw); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } - - private void testReadMethod(String command, Class[] proto, Object[] args, Options opts, JSONObject expected) throws Exception { - Class[] overloadedProto; - Object[] overloadedArgs; - Method mscommand; - - // With options and listener - overloadedProto = concat(proto, new Class[]{Options.class, ResponseListener.class}); - overloadedArgs = concat(args, new Object[]{opts, mock(ResponseListener.class)}); - mscommand = MemoryStorage.class.getDeclaredMethod(command, overloadedProto); - mscommand.invoke(ms, overloadedArgs); - verify(kuzzle).query((Kuzzle.QueryArgs) capturedQueryArgs.capture(), (JSONObject)capturedQuery.capture(), eq(opts), any(OnQueryDoneListener.class)); - validate(command, expected, true); - - // Without options, with listener - overloadedProto = concat(proto, new Class[]{ResponseListener.class}); - overloadedArgs = concat(args, new Object[]{mock(ResponseListener.class)}); - mscommand = MemoryStorage.class.getDeclaredMethod(command, overloadedProto); - mscommand.invoke(ms, overloadedArgs); - verify(kuzzle).query((Kuzzle.QueryArgs) capturedQueryArgs.capture(), (JSONObject)capturedQuery.capture(), eq((Options)null), any(OnQueryDoneListener.class)); - validate(command, expected, false); - } - - private void testWriteMethod(String command, Class[] proto, Object[] args, Options opts, JSONObject expected) throws Exception { - Class[] overloadedProto; - Object[] overloadedArgs; - Method mscommand = MemoryStorage.class.getDeclaredMethod(command, proto); - - // Without options nor listener - mscommand.invoke(ms, args); - verify(kuzzle).query((Kuzzle.QueryArgs) capturedQueryArgs.capture(), (JSONObject)capturedQuery.capture(), eq((Options)null)); - validate(command, expected, false); - - // With options, without listener - overloadedProto = concat(proto, new Class[]{Options.class}); - overloadedArgs = concat(args, new Object[]{opts}); - mscommand = MemoryStorage.class.getDeclaredMethod(command, overloadedProto); - mscommand.invoke(ms, overloadedArgs); - verify(kuzzle).query((Kuzzle.QueryArgs) capturedQueryArgs.capture(), (JSONObject)capturedQuery.capture(), eq(opts)); - validate(command, expected, true); - - // With options and listener - overloadedProto = concat(overloadedProto, new Class[]{ResponseListener.class}); - overloadedArgs = concat(overloadedArgs, new Object[]{mock(ResponseListener.class)}); - mscommand = MemoryStorage.class.getDeclaredMethod(command, overloadedProto); - mscommand.invoke(ms, overloadedArgs); - verify(kuzzle).query((Kuzzle.QueryArgs) capturedQueryArgs.capture(), (JSONObject)capturedQuery.capture(), eq(opts), any(OnQueryDoneListener.class)); - validate(command, expected, true); - - // Without options, with listener - overloadedProto = concat(proto, new Class[]{ResponseListener.class}); - overloadedArgs = concat(args, new Object[]{mock(ResponseListener.class)}); - mscommand = MemoryStorage.class.getDeclaredMethod(command, overloadedProto); - mscommand.invoke(ms, overloadedArgs); - verify(kuzzle).query((Kuzzle.QueryArgs) capturedQueryArgs.capture(), (JSONObject)capturedQuery.capture(), eq((Options)null), any(OnQueryDoneListener.class)); - validate(command, expected, false); - } - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - ms = new MemoryStorage(kuzzle); - capturedQueryArgs = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - capturedQuery = ArgumentCaptor.forClass(io.kuzzle.sdk.util.KuzzleJSONObject.class); - queryArgs.controller = "ms"; - } - - @Test - public void append() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("body", new JSONObject() - .put("value", "bar") - ); - - this.testWriteMethod("append", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.append("foo", "bar", listener); - } - - @Test - public void bitcount() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setStart((long)13) - .setEnd((long)42); - Object[] args = new Object[]{"foo"}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("start", 13) - .put("end", 42); - - this.testReadMethod("bitcount", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.bitcount("foo", listener); - } - - @Test - public void bitop() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar"}; - Object[] args = new Object[]{"foo", "xor", keys}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("body", new JSONObject() - .put("operation", "xor") - .put("keys", new JSONArray(Arrays.asList(keys))) - ); - - this.testWriteMethod("bitop", new Class[]{String.class, String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.bitop("foo", "bar", keys, listener); - } - - @Test - public void bitpos() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setStart((long)13) - .setEnd((long)42); - Object[] args = new Object[]{"foo", 1}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("bit", 1) - .put("start", 13) - .put("end", 42); - - this.testReadMethod("bitpos", new Class[]{String.class, int.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.bitpos("foo", 1, listener); - } - - @Test - public void dbsize() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{}; - JSONObject expected = new JSONObject(); - - this.testReadMethod("dbsize", new Class[]{}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.dbsize(listener); - } - - @Test - public void decr() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo"}; - JSONObject expected = new JSONObject().put("_id", "foo"); - - this.testWriteMethod("decr", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.decr("foo", listener); - } - - @Test - public void decrby() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo", -42}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("body", new JSONObject() - .put("value", -42) - ); - - this.testWriteMethod("decrby", new Class[]{String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.decrby("foo", -42, listener); - } - - @Test - public void del() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{keys}; - JSONObject expected = new JSONObject() - .put("body", new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))) - ); - - this.testWriteMethod("del", new Class[]{String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.del(keys, listener); - } - - @Test - public void exists() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{keys}; - JSONObject expected = new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))); - - this.testReadMethod("exists", new Class[]{String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.exists(keys, listener); - } - - @Test - public void expire() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo", 42}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("body", new JSONObject() - .put("seconds", 42) - ); - - this.testWriteMethod("expire", new Class[]{String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.expire("foo", 42, listener); - } - - @Test - public void expireat() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo", 42}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("body", new JSONObject() - .put("timestamp", 42) - ); - - this.testWriteMethod("expireat", new Class[]{String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.expireat("foo", 42, listener); - } - - @Test - public void flushdb() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{}; - JSONObject expected = new JSONObject(); - - this.testWriteMethod("flushdb", new Class[]{}, args, opts, expected); - - ResponseListener listener = verifyResultString("OK", "OK"); - ms.flushdb(listener); - } - - @Test - public void geoadd() throws Exception { - Options opts = new Options().setQueuable(true); - JSONObject[] points = new JSONObject[]{ - new JSONObject() - .put("lon", 13.361389) - .put("lat", 38.115556) - .put("name", "Palermo"), - new JSONObject() - .put("lon", 15.087269) - .put("lat", 37.502669) - .put("name", "Catania") - }; - Object[] args = new Object[]{"foo", points}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("body", new JSONObject() - .put("points", new JSONArray(Arrays.asList(points))) - ); - - this.testWriteMethod("geoadd", new Class[]{String.class, JSONObject[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.geoadd("foo", points, listener); - } - - @Test - public void geodist() throws Exception { - Options opts = new Options().setQueuable(true).setUnit("ft"); - Object[] args = new Object[]{"key", "Palermo", "Catania"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("member1", "Palermo") - .put("member2", "Catania") - .put("unit", "ft"); - - this.testReadMethod("geodist", new Class[]{String.class, String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultDouble("166274.1516", 166274.1516); - ms.geodist("foo", "Palermo", "Catania", listener); - } - - @Test - public void geohash() throws Exception { - Options opts = new Options().setQueuable(true); - String[] members = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", members}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("members", new JSONArray(Arrays.asList(members))); - - this.testReadMethod("geohash", new Class[]{String.class, String[].class}, args, opts, expected); - - String[] expectedResult = new String[]{"sqc8b49rny0", "sqdtr74hyu0"}; - JSONArray rawResult = new JSONArray().put("sqc8b49rny0").put("sqdtr74hyu0"); - ResponseListener listener = verifyResultStringArray(rawResult, expectedResult); - ms.geohash("key", members, listener); - } - - @Test - public void geopos() throws Exception { - Options opts = new Options().setQueuable(true); - String[] members = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", members}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("members", new JSONArray(Arrays.asList(members))); - - this.testReadMethod("geopos", new Class[]{String.class, String[].class}, args, opts, expected); - - JSONArray rawResult = new JSONArray() - .put(new JSONArray().put("13.361389").put("38.115556")) - .put(new JSONArray().put("15.087269").put("37.502669")); - - mockResult(new KuzzleJSONObject().put("result", rawResult)); - - final Double[][] expectedResult = new Double[][]{ - {13.361389, 38.115556}, - {15.087269, 37.502669} - }; - - ms.geopos("key", members, new ResponseListener() { - @Override - public void onSuccess(Double[][] response) { - for (int i = 0; i < response.length; i++) { - assertArrayEquals(response[i], expectedResult[i]); - } - } - - @Override - public void onError(JSONObject error) { - fail("onError callback should not have been invoked"); - } - }); - } - - @Test - public void georadius() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setCount((long)10) - .setSort("asc") - .setWithcoord(true) - .setWithdist(true); - Object[] args = new Object[]{"key", 15, 37, 200, "km"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("lon", 15) - .put("lat", 37) - .put("distance", 200) - .put("unit", "km"); - - this.testReadMethod("georadius", new Class[]{String.class, double.class, double.class, double.class, String.class}, args, opts, expected); - - // without coordinates nor distance - opts.setWithcoord(false).setWithdist(false); - ResponseListener listener = verifyResultJSONObjectArray( - new JSONArray().put("Palermo").put("Catania"), - new JSONObject[]{ - new JSONObject().put("name", "Palermo"), - new JSONObject().put("name", "Catania") - } - ); - ms.georadius("key", 15, 37, 200, "km", opts, listener); - - // with coordinates, without distance - opts.setWithcoord(true).setWithdist(false); - listener = verifyResultJSONObjectArray( - new JSONArray().put( - new JSONArray() - .put("Palermo").put("190.4424") - ).put( - new JSONArray() - .put("Catania").put("56.4413") - ), - new JSONObject[]{ - new JSONObject().put("name", "Palermo").put("distance", 190.4424), - new JSONObject().put("name", "Catania").put("distance", 56.4413) - } - ); - ms.georadius("key", 15, 37, 200, "km", opts, listener); - - // without coordinates, with distance - opts.setWithcoord(false).setWithdist(true); - listener = verifyResultJSONObjectArray( - new JSONArray().put( - new JSONArray() - .put("Palermo").put(new JSONArray().put("13.3613").put("38.1155")) - ).put( - new JSONArray() - .put("Catania").put(new JSONArray().put("15.0872").put("37.5026")) - ), - new JSONObject[]{ - new JSONObject().put("name", "Palermo") - .put("coordinates", new JSONArray().put(13.3613).put(38.1155)), - new JSONObject().put("name", "Catania") - .put("coordinates", new JSONArray().put(15.0872).put(37.5026)) - } - ); - ms.georadius("key", 15, 37, 200, "km", opts, listener); - - // with coordinates, with distance - opts.setWithcoord(true).setWithdist(true); - listener = verifyResultJSONObjectArray( - new JSONArray().put( - new JSONArray() - .put("Palermo").put(new JSONArray().put("13.3613").put("38.1155")).put("190.4424") - ).put( - new JSONArray() - .put("Catania").put("56.4413").put(new JSONArray().put("15.0872").put("37.5026")) - ), - new JSONObject[]{ - new JSONObject().put("name", "Palermo") - .put("distance", 190.4424) - .put("coordinates", new JSONArray().put(13.3613).put(38.1155)), - new JSONObject().put("name", "Catania") - .put("distance", 56.4413) - .put("coordinates", new JSONArray().put(15.0872).put(37.5026)) - } - ); - ms.georadius("key", 15, 37, 200, "km", opts, listener); - } - - @Test - public void georadiusbymember() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setCount((long)10) - .setSort("asc") - .setWithcoord(true) - .setWithdist(true); - Object[] args = new Object[]{"key", "Palermo", 200, "km"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("member", "Palermo") - .put("distance", 200) - .put("unit", "km"); - - this.testReadMethod("georadiusbymember", new Class[]{String.class, String.class, double.class, String.class}, args, opts, expected); - - // without coordinates nor distance - opts.setWithcoord(false).setWithdist(false); - ResponseListener listener = verifyResultJSONObjectArray( - new JSONArray().put("Palermo").put("Catania"), - new JSONObject[]{ - new JSONObject().put("name", "Palermo"), - new JSONObject().put("name", "Catania") - } - ); - ms.georadiusbymember("key", "Palermo", 200, "km", opts, listener); - - // with coordinates, without distance - opts.setWithcoord(true).setWithdist(false); - listener = verifyResultJSONObjectArray( - new JSONArray().put( - new JSONArray() - .put("Palermo").put("190.4424") - ).put( - new JSONArray() - .put("Catania").put("56.4413") - ), - new JSONObject[]{ - new JSONObject().put("name", "Palermo").put("distance", 190.4424), - new JSONObject().put("name", "Catania").put("distance", 56.4413) - } - ); - ms.georadiusbymember("key", "Palermo", 200, "km", opts, listener); - - // without coordinates, with distance - opts.setWithcoord(false).setWithdist(true); - listener = verifyResultJSONObjectArray( - new JSONArray().put( - new JSONArray() - .put("Palermo").put(new JSONArray().put("13.3613").put("38.1155")) - ).put( - new JSONArray() - .put("Catania").put(new JSONArray().put("15.0872").put("37.5026")) - ), - new JSONObject[]{ - new JSONObject().put("name", "Palermo") - .put("coordinates", new JSONArray().put(13.3613).put(38.1155)), - new JSONObject().put("name", "Catania") - .put("coordinates", new JSONArray().put(15.0872).put(37.5026)) - } - ); - ms.georadiusbymember("key", "Palermo", 200, "km", opts, listener); - - // with coordinates, with distance - opts.setWithcoord(true).setWithdist(true); - listener = verifyResultJSONObjectArray( - new JSONArray().put( - new JSONArray() - .put("Palermo").put(new JSONArray().put("13.3613").put("38.1155")).put("190.4424") - ).put( - new JSONArray() - .put("Catania").put("56.4413").put(new JSONArray().put("15.0872").put("37.5026")) - ), - new JSONObject[]{ - new JSONObject().put("name", "Palermo") - .put("distance", 190.4424) - .put("coordinates", new JSONArray().put(13.3613).put(38.1155)), - new JSONObject().put("name", "Catania") - .put("distance", 56.4413) - .put("coordinates", new JSONArray().put(15.0872).put(37.5026)) - } - ); - ms.georadiusbymember("key", "Palermo", 200, "km", opts, listener); - } - - @Test - public void get() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("get", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.get("key", listener); - } - - @Test - public void getbit() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 10}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("offset", 10); - - this.testReadMethod("getbit", new Class[]{String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.getbit("key", 10, listener); - } - - @Test - public void getrange() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 13, 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("start", 13) - .put("end", 42); - - this.testReadMethod("getrange", new Class[]{String.class, long.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.getrange("key", 13, 42, listener); - } - - @Test - public void getset() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "value"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject().put("value", "value")); - - this.testWriteMethod("getset", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.getset("key", "value", listener); - } - - @Test - public void hdel() throws Exception { - Options opts = new Options().setQueuable(true); - String[] fields = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", fields}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject().put("fields", new JSONArray(Arrays.asList(fields)))); - - this.testWriteMethod("hdel", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.hdel("key", fields, listener); - } - - @Test - public void hexists() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foobar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("field", "foobar"); - - this.testReadMethod("hexists", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(1, 1); - ms.hexists("key", "foobar", listener); - } - - @Test - public void hget() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("field", "foo"); - - this.testReadMethod("hget", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("bar", "bar"); - ms.hget("key", "foo", listener); - } - - @Test - public void hgetall() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("hgetall", new Class[]{String.class}, args, opts, expected); - - final KuzzleJSONObject result = new KuzzleJSONObject().put("foo", "bar"); - mockResult(new KuzzleJSONObject().put("result", result)); - - ResponseListener listener =new ResponseListener() { - @Override - public void onSuccess(JSONObject response) { - assertEquals(response, result); - } - - @Override - public void onError(JSONObject error) { - } - }; - - ms.hgetall("key", listener); - } - - @Test - public void hincrby() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", 42) - .put("field", "foo") - ); - - this.testWriteMethod("hincrby", new Class[]{String.class, String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.hincrby("foo", "bar", 42, listener); - } - - @Test - public void hincrbyfloat() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", 3.14159}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", 3.14159) - .put("field", "foo") - ); - - this.testWriteMethod("hincrbyfloat", new Class[]{String.class, String.class, double.class}, args, opts, expected); - - ResponseListener listener = verifyResultDouble("48.14159", 48.14159); - ms.hincrbyfloat("foo", "bar", 3.14159, listener); - } - - @Test - public void hkeys() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("hkeys", new Class[]{String.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.hkeys("key", listener); - } - - @Test - public void hlen() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("hlen", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.hlen("key", listener); - } - - @Test - public void hmget() throws Exception { - Options opts = new Options().setQueuable(true); - String[] fields = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", fields}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("fields", new JSONArray(Arrays.asList(fields))); - - this.testReadMethod("hmget", new Class[]{String.class, String[].class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - ResponseListener listener = verifyResultStringArray(result, fields); - ms.hmget("key", fields, listener); - } - - @Test - public void hmset() throws Exception { - Options opts = new Options().setQueuable(true); - JSONObject[] entries = new JSONObject[]{ - new JSONObject().put("field", "field1").put("value", "foo"), - new JSONObject().put("field", "field2").put("value", "bar"), - new JSONObject().put("field", "...").put("value", "...") - }; - - Object[] args = new Object[]{"key", entries}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("entries", new JSONArray(Arrays.asList(entries))) - ); - - this.testWriteMethod("hmset", new Class[]{String.class, JSONObject[].class}, args, opts, expected); - - ResponseListener listener = verifyResultString("OK", "OK"); - ms.hmset("key", entries, listener); - } - - @Test - public void hscan() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setCount((long)10) - .setMatch("foo*"); - Object[] args = new Object[]{"key", 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("cursor", 42) - .put("count", 10) - .put("match", "foo*"); - - this.testReadMethod("hscan", new Class[]{String.class, long.class}, args, opts, expected); - - JSONArray result = new JSONArray() - .put("18") - .put(new JSONArray() - .put("field1") - .put("field1 value") - .put("field2") - .put("field2 value") - ); - - JSONObject expectedResult = new JSONObject() - .put("cursor", 18) - .put("values", new JSONArray() - .put("field1") - .put("field1 value") - .put("field2") - .put("field2 value") - ); - - ResponseListener listener = verifyResultJSONObject(result, expectedResult); - ms.hscan("key", 42, listener); - } - - @Test - public void hset() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("field", "foo") - .put("value", "bar") - ); - - this.testWriteMethod("hset", new Class[]{String.class, String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.hset("key", "foo", "bar", listener); - } - - @Test - public void hsetnx() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("field", "foo") - .put("value", "bar") - ); - - this.testWriteMethod("hsetnx", new Class[]{String.class, String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.hsetnx("key", "foo", "bar", listener); - } - - @Test - public void hstrlen() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("field", "foo"); - - this.testReadMethod("hstrlen", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.hstrlen("key", "foo", listener); - } - - @Test - public void hvals() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("hvals", new Class[]{String.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.hvals("key", listener); - } - - @Test - public void incr() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo"}; - JSONObject expected = new JSONObject().put("_id", "foo"); - - this.testWriteMethod("incr", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.incr("foo", listener); - } - - @Test - public void incrby() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo", -42}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("body", new JSONObject() - .put("value", -42) - ); - - this.testWriteMethod("incrby", new Class[]{String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.incrby("foo", -42, listener); - } - - @Test - public void incrbyfloat() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo", 3.14159}; - JSONObject expected = new JSONObject() - .put("_id", "foo") - .put("body", new JSONObject() - .put("value", 3.14159) - ); - - this.testWriteMethod("incrbyfloat", new Class[]{String.class, double.class}, args, opts, expected); - - ResponseListener listener = verifyResultDouble("48.14159", 48.14159); - ms.incrbyfloat("foo", 3.14159, listener); - } - - @Test - public void keys() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"foo*"}; - JSONObject expected = new JSONObject() - .put("pattern", "foo*"); - - this.testReadMethod("keys", new Class[]{String.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.keys("foo*", listener); - } - - @Test - public void lindex() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 10}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("index", 10); - - this.testReadMethod("lindex", new Class[]{String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foo", "foo"); - ms.lindex("key", 10, listener); - } - - @Test - public void linsert() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "before", "foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", "bar") - .put("position", "before") - .put("pivot", "foo") - ); - - this.testWriteMethod("linsert", new Class[]{String.class, String.class, String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.linsert("key", "before", "foo", "bar", listener); - } - - @Test - public void llen() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("llen", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.llen("key", listener); - } - - @Test - public void lpop() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testWriteMethod("lpop", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.lpop("key", listener); - } - - @Test - public void lpush() throws Exception { - Options opts = new Options().setQueuable(true); - String[] values = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", values}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("values", new JSONArray(Arrays.asList(values))) - ); - - this.testWriteMethod("lpush", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.lpush("key", values, listener); - } - - @Test - public void lpushx() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "value"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject().put("value", "value")); - - this.testWriteMethod("lpushx", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.lpushx("key", "value", listener); - } - - @Test - public void lrange() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 13, 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("start", 13) - .put("stop", 42); - - this.testReadMethod("lrange", new Class[]{String.class, long.class, long.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.lrange("key", 13, 42, listener); - } - - @Test - public void lrem() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 42, "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", "bar") - .put("count", 42) - ); - - this.testWriteMethod("lrem", new Class[]{String.class, long.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.lrem("key", 42, "bar", listener); - } - - - @Test - public void lset() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 42, "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", "bar") - .put("index", 42) - ); - - this.testWriteMethod("lset", new Class[]{String.class, long.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foo", "foo"); - ms.lset("key", 42, "bar", listener); - } - - @Test - public void ltrim() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 13, 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("start", 13) - .put("stop", 42) - ); - - this.testWriteMethod("ltrim", new Class[]{String.class, long.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foo", "foo"); - ms.ltrim("key", 13, 42, listener); - } - - @Test - public void mget() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - - Object[] args = new Object[]{keys}; - JSONObject expected = new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))); - - this.testReadMethod("mget", new Class[]{String[].class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - ResponseListener listener = verifyResultStringArray(result, keys); - ms.mget(keys, listener); - } - - @Test - public void mset() throws Exception { - Options opts = new Options().setQueuable(true); - JSONObject[] entries = new JSONObject[]{ - new JSONObject().put("key", "key1").put("value", "foo"), - new JSONObject().put("key", "key2").put("value", "bar"), - new JSONObject().put("key", "...").put("value", "...") - }; - - Object[] args = new Object[]{entries}; - JSONObject expected = new JSONObject() - .put("body", new JSONObject() - .put("entries", new JSONArray(Arrays.asList(entries))) - ); - - this.testWriteMethod("mset", new Class[]{JSONObject[].class}, args, opts, expected); - - ResponseListener listener = verifyResultString("OK", "OK"); - ms.mset(entries, listener); - } - - - @Test - public void msetnx() throws Exception { - Options opts = new Options().setQueuable(true); - JSONObject[] entries = new JSONObject[]{ - new JSONObject().put("key", "key1").put("value", "foo"), - new JSONObject().put("key", "key2").put("value", "bar"), - new JSONObject().put("key", "...").put("value", "...") - }; - - Object[] args = new Object[]{entries}; - JSONObject expected = new JSONObject() - .put("body", new JSONObject() - .put("entries", new JSONArray(Arrays.asList(entries))) - ); - - this.testWriteMethod("msetnx", new Class[]{JSONObject[].class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.msetnx(entries, listener); - } - - @Test - public void object() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "encoding"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("subcommand", "encoding"); - - this.testReadMethod("object", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.object("key", "encoding", listener); - } - - @Test - public void persist() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testWriteMethod("persist", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.persist("key", listener); - } - - @Test - public void pexpire() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 42000}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("milliseconds", 42000) - ); - - this.testWriteMethod("pexpire", new Class[]{String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.pexpire("key", 42000, listener); - } - - @Test - public void pexpireat() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 1234567890}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("timestamp", 1234567890) - ); - - this.testWriteMethod("pexpireat", new Class[]{String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.pexpireat("key", 1234567890, listener); - } - - @Test - public void pfadd() throws Exception { - Options opts = new Options().setQueuable(true); - String[] elements = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", elements}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("elements", new JSONArray(Arrays.asList(elements))) - ); - - this.testWriteMethod("pfadd", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(123, 123); - ms.pfadd("key", elements, listener); - } - - @Test - public void pfcount() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{keys}; - JSONObject expected = new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))); - - this.testReadMethod("pfcount", new Class[]{String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.pfcount(keys, listener); - } - - @Test - public void pfmerge() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar" , "baz"}; - Object[] args = new Object[]{"key", keys}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("sources", new JSONArray(Arrays.asList(keys))) - ); - - this.testWriteMethod("pfmerge", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultString("OK", "OK"); - ms.pfmerge("key", keys, listener); - } - - @Test - public void ping() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{}; - JSONObject expected = new JSONObject(); - - this.testReadMethod("ping", new Class[]{}, args, opts, expected); - - ResponseListener listener = verifyResultString("OK", "OK"); - ms.ping(listener); - } - - @Test - public void psetex() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", 42000}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", "foo") - .put("milliseconds", 42000) - ); - - this.testWriteMethod("psetex", new Class[]{String.class, String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("OK", "OK"); - ms.psetex("key", "foo", 42000, listener); - } - - @Test - public void pttl() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("pttl", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.pttl("key", listener); - } - - @Test - public void randomkey() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{}; - JSONObject expected = new JSONObject(); - - this.testReadMethod("randomkey", new Class[]{}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.randomkey(listener); - } - - @Test - public void rename() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("newkey", "foo") - ); - - this.testWriteMethod("rename", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("OK", "OK"); - ms.rename("key", "foo", listener); - } - - @Test - public void renamenx() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("newkey", "foo") - ); - - this.testWriteMethod("renamenx", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(1, 1); - ms.renamenx("key", "foo", listener); - } - - @Test - public void rpop() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testWriteMethod("rpop", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.rpop("key", listener); - } - - @Test - public void rpoplpush() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "dest"}; - JSONObject expected = new JSONObject() - .put("body", new JSONObject() - .put("source", "key") - .put("destination", "dest") - ); - - this.testWriteMethod("rpoplpush", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.rpoplpush("key", "dest", listener); - } - - @Test - public void rpush() throws Exception { - Options opts = new Options().setQueuable(true); - String[] values = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", values}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("values", new JSONArray(Arrays.asList(values))) - ); - - this.testWriteMethod("rpush", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.rpush("key", values, listener); - } - - @Test - public void rpushx() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "value"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject().put("value", "value")); - - this.testWriteMethod("rpushx", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.rpushx("key", "value", listener); - } - - @Test - public void sadd() throws Exception { - Options opts = new Options().setQueuable(true); - String[] members = new String[]{"foo", "bar", "baz"}; - - Object[] args = new Object[]{"key", members}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("members", new JSONArray(Arrays.asList(members))) - ); - - this.testWriteMethod("sadd", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.sadd("key", members, listener); - } - - @Test - public void scan() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setCount((long)10) - .setMatch("foo*"); - Object[] args = new Object[]{42}; - JSONObject expected = new JSONObject() - .put("cursor", 42) - .put("count", 10) - .put("match", "foo*"); - - this.testReadMethod("scan", new Class[]{long.class}, args, opts, expected); - - JSONArray result = new JSONArray() - .put("18") - .put(new JSONArray() - .put("field1") - .put("field1 value") - .put("field2") - .put("field2 value") - ); - - JSONObject expectedResult = new JSONObject() - .put("cursor", 18) - .put("values", result.getJSONArray(1)); - - ResponseListener listener = verifyResultJSONObject(result, expectedResult); - ms.scan(42, listener); - } - - @Test - public void scard() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("scard", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.scard("key", listener); - } - - @Test - public void sdiff() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", keys}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("keys", new JSONArray(Arrays.asList(keys))); - - this.testReadMethod("sdiff", new Class[]{String.class, String[].class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - ResponseListener listener = verifyResultStringArray(result, keys); - ms.sdiff("key", keys, listener); - } - - @Test - public void sdiffstore() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", keys, "dest"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))) - .put("destination", "dest") - ); - - this.testWriteMethod("sdiffstore", new Class[]{String.class, String[].class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.sdiffstore("key", keys, "dest", listener); - } - - @Test - public void set() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setEx((long)123) - .setNx(true) - .setPx((long)456) - .setXx(false); - Object[] args = new Object[]{"key", "value"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", "value") - .put("ex", 123) - .put("nx", true) - .put("px", 456) - .put("xx", false) - ); - - this.testWriteMethod("set", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.set("key", "value", listener); - } - - @Test - public void setex() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", "foo") - .put("seconds", 42) - ); - - this.testWriteMethod("setex", new Class[]{String.class, String.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("OK", "OK"); - ms.setex("key", "foo", 42, listener); - } - - @Test - public void setnx() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "value"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject().put("value", "value")); - - this.testWriteMethod("setnx", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(1, 1); - ms.setnx("key", "value", listener); - } - - @Test - public void sinter() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{keys}; - JSONObject expected = new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))); - - this.testReadMethod("sinter", new Class[]{String[].class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - ResponseListener listener = verifyResultStringArray(result, keys); - ms.sinter(keys, listener); - } - - @Test - public void sinterstore() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", keys}; - JSONObject expected = new JSONObject() - .put("body", new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))) - .put("destination", "key") - ); - - this.testWriteMethod("sinterstore", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.sinterstore("key", keys, listener); - } - - @Test - public void sismember() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("member", "foo"); - - this.testReadMethod("sismember", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(1, 1); - ms.sismember("key", "foo", listener); - } - - @Test - public void smembers() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("smembers", new Class[]{String.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.smembers("key", listener); - } - - @Test - public void smove() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("destination", "foo") - .put("member", "bar") - ); - - this.testWriteMethod("smove", new Class[]{String.class, String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultInt(1, 1); - ms.smove("key", "foo", "bar", listener); - } - - @Test - public void sort() throws Exception { - String[] array = new String[]{"foo", "bar", "baz"}; - Integer[] limit = new Integer[]{13, 42}; - Options opts = new Options() - .setQueuable(true) - .setAlpha(true) - .setBy("foobar") - .setDirection("asc") - .setGet(array) - .setLimit(limit); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("alpha", true) - .put("by", "foobar") - .put("direction", "asc") - .put("get", new JSONArray(Arrays.asList(array))) - .put("limit", new JSONArray(Arrays.asList(limit))); - - this.testReadMethod("sort", new Class[]{String.class}, args, opts, expected); - - JSONArray rawResult = new JSONArray().put("foo").put("bar").put("baz"); - ResponseListener listener = verifyResultStringArray(rawResult, array); - ms.sort("key", listener); - } - - @Test - public void spop() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setCount((long)10); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject().put("count", 10)); - - this.testWriteMethod("spop", new Class[]{String.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.spop("key", listener); - - listener = verifyResultStringArray("foo", new String[]{"foo"}); - ms.spop("key", listener); - } - - @Test - public void srandmember() throws Exception { - Options opts = new Options().setQueuable(true).setCount((long)10); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("count", 10); - - this.testReadMethod("srandmember", new Class[]{String.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.srandmember("key", listener); - - listener = verifyResultStringArray("foo", new String[]{"foo"}); - ms.srandmember("key", listener); - } - - @Test - public void srem() throws Exception { - Options opts = new Options().setQueuable(true); - String[] members = new String[]{"foo", "bar", "baz"}; - - Object[] args = new Object[]{"key", members}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("members", new JSONArray(Arrays.asList(members))) - ); - - this.testWriteMethod("srem", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.srem("key", members, listener); - } - - @Test - public void sscan() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setCount((long)10) - .setMatch("foo*"); - Object[] args = new Object[]{"key", 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("cursor", 42) - .put("count", 10) - .put("match", "foo*"); - - this.testReadMethod("sscan", new Class[]{String.class, long.class}, args, opts, expected); - - JSONArray result = new JSONArray() - .put("18") - .put(new JSONArray() - .put("field1") - .put("field1 value") - .put("field2") - .put("field2 value") - ); - - JSONObject expectedResult = new JSONObject() - .put("cursor", 18) - .put("values", result.getJSONArray(1)); - - ResponseListener listener = verifyResultJSONObject(result, expectedResult); - ms.sscan("key", 42, listener); - } - - @Test - public void strlen() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("strlen", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.strlen("key", listener); - } - - @Test - public void sunion() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{keys}; - JSONObject expected = new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))); - - this.testReadMethod("sunion", new Class[]{String[].class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - ResponseListener listener = verifyResultStringArray(result, keys); - ms.sunion(keys, listener); - } - - @Test - public void sunionstore() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", keys}; - JSONObject expected = new JSONObject() - .put("body", new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))) - .put("destination", "key") - ); - - this.testWriteMethod("sunionstore", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.sunionstore("key", keys, listener); - } - - @Test - public void time() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{}; - JSONObject expected = new JSONObject(); - - this.testReadMethod("time", new Class[]{}, args, opts, expected); - - mockResult(new KuzzleJSONObject().put("result", new JSONArray().put("123").put("456"))); - - ms.time(new ResponseListener() { - @Override - public void onSuccess(Long[] response) { - assertArrayEquals(response, new Long[]{Long.valueOf(123), Long.valueOf(456)}); - } - - @Override - public void onError(JSONObject error) { - - } - }); - } - - @Test - public void touch() throws Exception { - Options opts = new Options().setQueuable(true); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{keys}; - JSONObject expected = new JSONObject() - .put("body", new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))) - ); - - this.testWriteMethod("touch", new Class[]{String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.touch(keys, listener); - } - - @Test - public void ttl() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("ttl", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.ttl("key", listener); - } - - @Test - public void type() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("type", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultString("foobar", "foobar"); - ms.type("key", listener); - } - - @Test - public void zadd() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setCh(true) - .setIncr(true) - .setNx(true) - .setXx(false); - JSONObject[] elements = new JSONObject[]{ - new JSONObject().put("score", 1).put("member", "foo"), - new JSONObject().put("score", 2).put("member", "bar"), - new JSONObject().put("score", 3).put("member", "baz") - }; - - - Object[] args = new Object[]{"key", elements}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("elements", new JSONArray(Arrays.asList(elements))) - .put("ch", true) - .put("incr", true) - .put("nx", true) - .put("xx", false) - ); - - this.testWriteMethod("zadd", new Class[]{String.class, JSONObject[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zadd("key", elements, listener); - } - - @Test - public void zcard() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key"}; - JSONObject expected = new JSONObject() - .put("_id", "key"); - - this.testReadMethod("zcard", new Class[]{String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zcard("key", listener); - } - - @Test - public void zcount() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 13, 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("min", 13) - .put("max", 42); - - this.testReadMethod("zcount", new Class[]{String.class, long.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zcount("key", 13, 42, listener); - } - - @Test - public void zincrby() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", 3.14159}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("value", 3.14159) - .put("member", "foo") - ); - - this.testWriteMethod("zincrby", new Class[]{String.class, String.class, double.class}, args, opts, expected); - - ResponseListener listener = verifyResultDouble("48.14159", 48.14159); - ms.zincrby("foo", "bar", 3.14159, listener); - } - - @Test - public void zinterstore() throws Exception { - Integer[] weights = new Integer[]{1, 2, 3}; - Options opts = new Options() - .setQueuable(true) - .setAggregate("max") - .setWeights(weights); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", keys}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))) - .put("aggregate", "max") - .put("weights", new JSONArray(Arrays.asList(weights))) - ); - - this.testWriteMethod("zinterstore", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zinterstore("key", keys, listener); - } - - @Test - public void zlexcount() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("min", "foo") - .put("max", "bar"); - - this.testReadMethod("zlexcount", new Class[]{String.class, String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zlexcount("key", "foo", "bar", listener); - } - - @Test - public void zrange() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 13, 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("start", 13) - .put("stop", 42) - .put("options", new JSONArray().put("withscores")); - - this.testReadMethod("zrange", new Class[]{String.class, long.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultJSONObjectArray( - new JSONArray().put("foo").put("3.14159").put("bar").put("123.456"), - new JSONObject[]{ - new JSONObject().put("member", "foo").put("score", 3.14159), - new JSONObject().put("member", "bar").put("score", 123.456) - } - ); - ms.zrange("key", 13, 42, listener); - } - - @Test - public void zrangebylex() throws Exception { - Integer[] limit = new Integer[]{1, 2}; - Options opts = new Options() - .setQueuable(true) - .setLimit(limit); - Object[] args = new Object[]{"key", "foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("min", "foo") - .put("max", "bar") - .put("limit", new JSONArray(Arrays.asList(limit))); - - this.testReadMethod("zrangebylex", new Class[]{String.class, String.class, String.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.zrangebylex("key", "foo", "bar", listener); - } - - @Test - public void zrangebyscore() throws Exception { - Integer[] limit = new Integer[]{1, 2}; - Options opts = new Options() - .setQueuable(true) - .setLimit(limit); - Object[] args = new Object[]{"key", 3.14, 42.24}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("min", 3.14) - .put("max", 42.24) - .put("limit", new JSONArray(Arrays.asList(limit))) - .put("options", new JSONArray().put("withscores")); - - this.testReadMethod("zrangebyscore", new Class[]{String.class, double.class, double.class}, args, opts, expected); - - ResponseListener listener = verifyResultJSONObjectArray( - new JSONArray().put("foo").put("3.14159").put("bar").put("123.456"), - new JSONObject[]{ - new JSONObject().put("member", "foo").put("score", 3.14159), - new JSONObject().put("member", "bar").put("score", 123.456) - } - ); - ms.zrangebyscore("key", 3.14, 42.24, listener); - } - - @Test - public void zrank() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("member", "foo"); - - this.testReadMethod("zrank", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zrank("key", "foo", listener); - } - - @Test - public void zrem() throws Exception { - Options opts = new Options().setQueuable(true); - String[] members = new String[]{"foo", "bar", "baz"}; - - Object[] args = new Object[]{"key", members}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("members", new JSONArray(Arrays.asList(members))) - ); - - this.testWriteMethod("zrem", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zrem("key", members, listener); - } - - @Test - public void zremrangebylex() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("min", "foo") - .put("max", "bar") - ); - - this.testWriteMethod("zremrangebylex", new Class[]{String.class, String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zremrangebylex("key", "foo", "bar", listener); - } - - @Test - public void zremrangebyrank() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 13, 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("start", 13) - .put("stop", 42) - ); - - this.testWriteMethod("zremrangebyrank", new Class[]{String.class, long.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zremrangebyrank("key", 13, 42, listener); - } - - @Test - public void zremrangebyscore() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 13.1, 42.3}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("min", 13.1) - .put("max", 42.3) - ); - - this.testWriteMethod("zremrangebyscore", new Class[]{String.class, double.class, double.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zremrangebyscore("key", 13, 42, listener); - } - - @Test - public void zrevrange() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", 13, 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("start", 13) - .put("stop", 42) - .put("options", new JSONArray().put("withscores")); - - this.testReadMethod("zrevrange", new Class[]{String.class, long.class, long.class}, args, opts, expected); - - ResponseListener listener = verifyResultJSONObjectArray( - new JSONArray().put("foo").put("3.14159").put("bar").put("123.456"), - new JSONObject[]{ - new JSONObject().put("member", "foo").put("score", 3.14159), - new JSONObject().put("member", "bar").put("score", 123.456) - } - ); - ms.zrevrange("key", 13, 42, listener); - } - - @Test - public void zrevrangebylex() throws Exception { - Integer[] limit = new Integer[]{1, 2}; - Options opts = new Options() - .setQueuable(true) - .setLimit(limit); - Object[] args = new Object[]{"key", "foo", "bar"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("min", "foo") - .put("max", "bar") - .put("limit", new JSONArray(Arrays.asList(limit))); - - this.testReadMethod("zrevrangebylex", new Class[]{String.class, String.class, String.class}, args, opts, expected); - - JSONArray result = new JSONArray().put("foo").put("bar").put("baz"); - String[] expectedResult = new String[]{"foo", "bar", "baz"}; - ResponseListener listener = verifyResultStringArray(result, expectedResult); - ms.zrevrangebylex("key", "foo", "bar", listener); - } - - @Test - public void zrevrangebyscore() throws Exception { - Integer[] limit = new Integer[]{1, 2}; - Options opts = new Options() - .setQueuable(true) - .setLimit(limit); - Object[] args = new Object[]{"key", 3.14, 42.24}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("min", 3.14) - .put("max", 42.24) - .put("limit", new JSONArray(Arrays.asList(limit))) - .put("options", new JSONArray().put("withscores")); - - this.testReadMethod("zrevrangebyscore", new Class[]{String.class, double.class, double.class}, args, opts, expected); - - ResponseListener listener = verifyResultJSONObjectArray( - new JSONArray().put("foo").put("3.14159").put("bar").put("123.456"), - new JSONObject[]{ - new JSONObject().put("member", "foo").put("score", 3.14159), - new JSONObject().put("member", "bar").put("score", 123.456) - } - ); - ms.zrevrangebyscore("key", 3.14, 42.24, listener); - } - - @Test - public void zrevrank() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("member", "foo"); - - this.testReadMethod("zrevrank", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zrevrank("key", "foo", listener); - } - - @Test - public void zscan() throws Exception { - Options opts = new Options() - .setQueuable(true) - .setCount((long)10) - .setMatch("foo*"); - Object[] args = new Object[]{"key", 42}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("cursor", 42) - .put("count", 10) - .put("match", "foo*"); - - this.testReadMethod("zscan", new Class[]{String.class, long.class}, args, opts, expected); - - JSONArray result = new JSONArray() - .put("18") - .put(new JSONArray() - .put("field1") - .put("field1 value") - .put("field2") - .put("field2 value") - ); - - JSONObject expectedResult = new JSONObject() - .put("cursor", 18) - .put("values", result.getJSONArray(1)); - - ResponseListener listener = verifyResultJSONObject(result, expectedResult); - ms.zscan("key", 42, listener); - } - - @Test - public void zscore() throws Exception { - Options opts = new Options().setQueuable(true); - Object[] args = new Object[]{"key", "foo"}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("member", "foo"); - - this.testReadMethod("zscore", new Class[]{String.class, String.class}, args, opts, expected); - - ResponseListener listener = verifyResultDouble("3.14159", 3.14159); - ms.zscore("key", "foo", listener); - } - - @Test - public void zunionstore() throws Exception { - Integer[] weights = new Integer[]{1, 2, 3}; - Options opts = new Options() - .setQueuable(true) - .setAggregate("max") - .setWeights(weights); - String[] keys = new String[]{"foo", "bar", "baz"}; - Object[] args = new Object[]{"key", keys}; - JSONObject expected = new JSONObject() - .put("_id", "key") - .put("body", new JSONObject() - .put("keys", new JSONArray(Arrays.asList(keys))) - .put("aggregate", "max") - .put("weights", new JSONArray(Arrays.asList(weights))) - ); - - this.testWriteMethod("zunionstore", new Class[]{String.class, String[].class}, args, opts, expected); - - ResponseListener listener = verifyResultLong(123, 123); - ms.zunionstore("key", keys, listener); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/constructorTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/constructorTest.java deleted file mode 100644 index c053acb4..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/constructorTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleRoom; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.core.RoomOptions; -import io.kuzzle.sdk.listeners.ResponseListener; -import main.java.io.kuzzle.sdk.testUtils.RoomExtend; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -public class constructorTest { - private ResponseListener listener = mock(ResponseListener.class); - private JSONObject mockNotif = new JSONObject(); - private JSONObject mockResponse = new JSONObject(); - private Kuzzle k; - private RoomExtend room; - - @Before - public void setUp() throws JSONException { - mockNotif.put("type", "type") - .put("index", "index") - .put("status", 200) - .put("collection", "collection") - .put("controller", "controller") - .put("action", "action") - .put("state", "ALL") - .put("scope", "ALL") - .put("volatile", new JSONObject()) - .put("result", new JSONObject()) - .put("requestId", "42"); - mockResponse.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - k = mock(Kuzzle.class); - when(k.getHeaders()).thenReturn(new JSONObject()); - room = new RoomExtend(new Collection(k, "test", "index")); - } - - @Test - public void setSubscribeToSelfThroughConstructor() throws JSONException { - JSONObject meta = new JSONObject(); - meta.put("foo", "bar"); - RoomOptions options = new RoomOptions(); - options.setSubscribeToSelf(false); - Room room = new Room(new Collection(k, "test", "index"), options); - assertEquals(room.isSubscribeToSelf(), false); - room.setSubscribeToSelf(true); - assertEquals(room.isSubscribeToSelf(), true); - } - - @Test(expected = RuntimeException.class) - public void testConstructorException() { - Collection fake = spy(new Collection(k, "test", "index")); - doThrow(JSONException.class).when(fake).getHeaders(); - room = new RoomExtend(fake); - } - - @Test - public void testSetHeaders() throws JSONException { - room.makeHeadersNull(); - JSONObject headers = new JSONObject(); - headers.put("foo", "bar"); - room.setHeaders(headers, true); - assertEquals(room.getHeaders().getString("foo"), "bar"); - headers.put("oof", "baz"); - room.setHeaders(headers); - assertEquals(room.getHeaders().getString("foo"), "bar"); - assertEquals(room.getHeaders().getString("oof"), "baz"); - } - - @Test(expected = RuntimeException.class) - public void testSetHeadersException() { - JSONObject json = spy(new JSONObject()); - doThrow(JSONException.class).when(json).keys(); - room.setHeaders(json, false); - } - - @Test - public void testGetHeaders() throws JSONException { - room.setHeaders(null); - assertNotNull(room.getHeaders()); - JSONObject headers = new JSONObject(); - headers.put("foo", "bar"); - room.setHeaders(headers); - assertEquals(room.getHeaders().getString("foo"), "bar"); - } - - @Test - public void testFilters() throws JSONException { - JSONObject filters = new JSONObject(); - filters.put("foo", "bar"); - - room.renew(filters, listener, null); - assertEquals(room.getFilters().getString("foo"), "bar"); - JSONObject filters2 = new JSONObject(); - filters2.put("foo", "rab"); - room.setFilters(filters2); - assertEquals(room.getFilters().getString("foo"), "rab"); - } - - @Test - public void setVolatileThroughConstructor() throws JSONException { - JSONObject meta = new JSONObject(); - meta.put("foo", "bar"); - RoomOptions options = new RoomOptions(); - options.setVolatile(meta); - Room room = new Room(new Collection(k, "test", "index"), options); - assertEquals(room.getVolatile().get("foo"), "bar"); - JSONObject meta2 = new JSONObject(); - meta2.put("oof", "rab"); - room.setVolatile(meta2); - assertEquals(room.getVolatile().get("oof"), "rab"); - } - - @Test(expected = IllegalArgumentException.class) - public void testConstructorWithNullCollection() { - // Should throw an exception - new Room(null); - } - - @Test - public void testCollection() { - Collection collection = new Collection(k, "test", "index"); - Room room = new Room(collection); - assertEquals(room.getCollection(), collection.getCollection()); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/countTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/countTest.java deleted file mode 100644 index d31c7b95..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/countTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleRoom; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import main.java.io.kuzzle.sdk.testUtils.RoomExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class countTest { - private ResponseListener listener = mock(ResponseListener.class); - private ResponseListener spyListener = spy(new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); - private JSONObject mockNotif = new JSONObject(); - private JSONObject mockResponse = new JSONObject(); - private KuzzleExtend k; - private RoomExtend room; - - @Before - public void setUp() throws JSONException, URISyntaxException { - mockNotif.put("type", "type") - .put("index", "index") - .put("status", 200) - .put("collection", "collection") - .put("controller", "controller") - .put("action", "action") - .put("state", "ALL") - .put("scope", "ALL") - .put("volatile", new JSONObject()) - .put("result", new JSONObject()) - .put("requestId", "42"); - mockResponse.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - k = spy(new KuzzleExtend("localhost", null, null)); - k.setSocket(mock(WebSocketClient.class)); - k.setState(States.CONNECTED); - when(k.getHeaders()).thenReturn(new JSONObject()); - room = new RoomExtend(new Collection(k, "test", "index")); - } - - @Test(expected = IllegalArgumentException.class) - public void testCountIllegalArgument() { - room.count(null); - } - - @Test - public void testCountWhileSubscribing() throws JSONException, URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - extended = spy(extended); - room = new RoomExtend(new Collection(extended, "test", "index")); - room.setRoomId("foobar"); - room.setSubscribing(true); - room.count(spyListener); - room = spy(room); - room.setSubscribing(false); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - //Mock response - JSONObject result = new JSONObject(); - result.put("result", new JSONObject() - .put("channel", "channel") - .put("roomId", "42") - .put("count", 42)); - //Call callback with response - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - verify(room).dequeue(); - - } - return null; - } - }).when(extended).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - room.renew(listener); - } - - @Test(expected = RuntimeException.class) - public void testCountQueryException() throws JSONException { - room.setRoomId("foobar"); - doThrow(JSONException.class).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(OnQueryDoneListener.class)); - room.count(listener); - } - - @Test(expected = RuntimeException.class) - public void testCountException() throws JSONException { - room.setRoomId("foobar"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[2]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - return null; - } - }).when(k).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(Integer.class)); - room.count(listener); - } - - @Test(expected = IllegalStateException.class) - public void testCountNoId() { - room.count(listener); - } - - @Test - public void testCount() throws JSONException, URISyntaxException { - JSONObject o = mock(JSONObject.class); - when(o.put(any(String.class), any(Object.class))).thenReturn(new JSONObject()); - - KuzzleExtend extended = new KuzzleExtend("localhost", null, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - extended = spy(extended); - room = new RoomExtend(new Collection(extended, "test", "index")); - room.setRoomId("foobar"); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener)invocation.getArguments()[2]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - ((OnQueryDoneListener)invocation.getArguments()[2]).onError(new JSONObject()); - return null; - } - }).when(extended).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(OnQueryDoneListener.class)); - room.setRoomId("foobar"); - room.count(mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(extended, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "realtime"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "count"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/notificationHandlerTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/notificationHandlerTest.java deleted file mode 100644 index e2686350..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/notificationHandlerTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleRoom; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; -import java.util.Date; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.RoomOptions; -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.EventListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import main.java.io.kuzzle.sdk.testUtils.RoomExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class notificationHandlerTest { - private ResponseListener listener = mock(ResponseListener.class); - private JSONObject mockNotif = new JSONObject(); - private JSONObject mockResponse = new JSONObject(); - private Kuzzle k; - private RoomExtend room; - - @Before - public void setUp() throws JSONException { - mockNotif.put("type", "type") - .put("index", "index") - .put("status", 200) - .put("collection", "collection") - .put("controller", "controller") - .put("action", "action") - .put("state", "all") - .put("scope", "all") - .put("volatile", new JSONObject()) - .put("result", new JSONObject()) - .put("requestId", "42"); - mockResponse.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - k = mock(Kuzzle.class); - when(k.getHeaders()).thenReturn(new JSONObject()); - room = new RoomExtend(new Collection(k, "test", "index")); - } - - @Test(expected = IllegalArgumentException.class) - public void testCallAfterRenewWithNoResponse() { - RoomExtend renew = new RoomExtend(new Collection(k, "test", "index")); - // Should throw an exception - renew.callAfterRenew(null); - } - - @Test - public void testCallAfterRenew() throws JSONException { - RoomExtend renew = new RoomExtend(new Collection(k, "test", "index")); - renew.setListener(listener); - JSONObject mockResponse = new JSONObject().put("result", new JSONObject()); - mockResponse.put("requestId", "42"); - renew.callAfterRenew(mockNotif); - } - - @Test - public void testCallAfterRenewWithSubscribeToSelf() throws JSONException, URISyntaxException { - RoomOptions options = new RoomOptions(); - options.setSubscribeToSelf(true); - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - WebSocketClient s = mock(WebSocketClient.class); - extended.setSocket(s); - extended.setState(States.CONNECTED); - extended = spy(extended); - RoomExtend renew = new RoomExtend(new Collection(extended, "test", "index"), options); - renew.setListener(listener); - extended.getRequestHistory().put("42", new Date()); - renew.callAfterRenew(mockNotif); - verify(listener, atLeastOnce()).onSuccess(any(JSONObject.class)); - } - - @Test - public void testRenewOn() throws JSONException, URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - WebSocketClient s = mock(WebSocketClient.class); - extended.setSocket(s); - extended.setState(States.CONNECTED); - extended = spy(extended); - room = new RoomExtend(new Collection(extended, "collection", "index")); - room.setRoomId("foobar"); - room = spy(room); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - //Mock response - JSONObject result = new JSONObject(); - result.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - //Call callback with response - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - return null; - } - }).when(extended).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - room.renew(listener); - } - - @Test - public void testTokenExpiredNotification() throws JSONException, URISyntaxException { - k = new Kuzzle("localhost"); - EventListener listener = spy(new EventListener() { - @Override - public void trigger(Object... args) { - - } - }); - k.addListener(Event.tokenExpired, listener); - RoomExtend renew = new RoomExtend(new Collection(k, "test", "index")); - renew.setListener(mock(ResponseListener.class)); - JSONObject mockResponse = new JSONObject().put("result", new JSONObject()); - mockResponse.put("requestId", "42"); - mockNotif.put("type", "TokenExpired"); - renew.callAfterRenew(mockNotif); - verify(listener, times(1)).trigger(); - } - - @Test(expected = RuntimeException.class) - public void testCallAfterRenewException() throws URISyntaxException, JSONException { - RoomOptions options = new RoomOptions(); - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - WebSocketClient s = mock(WebSocketClient.class); - extended.setSocket(s); - extended.setState(States.CONNECTED); - extended = spy(extended); - RoomExtend renew = new RoomExtend(new Collection(extended, "test", "index"), options); - mockNotif = spy(mockNotif); - doThrow(JSONException.class).when(mockNotif).isNull(any(String.class)); - renew.setListener(listener); - extended.getRequestHistory().put("42", new Date()); - mockNotif.put("error", mock(JSONObject.class)); - renew.callAfterRenew(mockNotif); - // should trigger listener.onError - verify(listener, atLeastOnce()).onError(any(JSONObject.class)); - // Now simulate exception on the onError - doThrow(JSONException.class).when(listener).onError(any(JSONObject.class)); - mockNotif.remove("error"); - renew.callAfterRenew(mockNotif); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/renewTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/renewTest.java deleted file mode 100644 index 3110beaf..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/renewTest.java +++ /dev/null @@ -1,166 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleRoom; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.NotificationResponse; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import main.java.io.kuzzle.sdk.testUtils.RoomExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class renewTest { - @Mock - private ResponseListener listener; - - private JSONObject mockNotif = new JSONObject(); - private JSONObject mockResponse = new JSONObject(); - private Kuzzle k; - private RoomExtend room; - - @Before - public void setUp() throws JSONException { - mockNotif.put("type", "type") - .put("index", "index") - .put("status", 200) - .put("collection", "collection") - .put("controller", "controller") - .put("action", "action") - .put("state", "ALL") - .put("scope", "ALL") - .put("volatile", new JSONObject()) - .put("result", new JSONObject()) - .put("requestId", "42"); - mockResponse.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - k = mock(Kuzzle.class); - when(k.getHeaders()).thenReturn(new JSONObject()); - room = new RoomExtend(new Collection(k, "text", "index")); - - MockitoAnnotations.initMocks(this); - } - - @Test(expected = IllegalArgumentException.class) - public void testRenewIllegalListener() { - room.renew(null, null); - } - - @Test - public void testRenew() throws JSONException, URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - WebSocketClient s = mock(WebSocketClient.class); - KuzzleExtend kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setState(States.CONNECTED); - kuzzle.setSocket(s); - - final Kuzzle kuzzleSpy = spy(kuzzle); - Room testRoom = new Room(new Collection(kuzzleSpy, "collection", "index")); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - //Mock response - JSONObject result = new JSONObject(); - result.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - //Call callback with response - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzleSpy, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "realtime"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "subscribe"); - - return null; - } - }).when(kuzzleSpy).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - testRoom.renew(new JSONObject(), listener, null); - } - - @Test - public void testNoRenewal() throws JSONException, URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - KuzzleExtend kuzzle = new KuzzleExtend("localhost", options, null); - kuzzle.setState(States.CONNECTED); - kuzzle.setSocket(mock(WebSocketClient.class)); - - final Kuzzle kuzzleSpy = spy(kuzzle); - RoomExtend testRoom = new RoomExtend(new Collection(kuzzleSpy, "collection", "index")); - testRoom.setRoomId("foobar"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - //Mock response - JSONObject result = new JSONObject(); - result.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - //Call callback with response - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - verify(kuzzleSpy, times(1)).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - return null; - } - }).when(kuzzleSpy).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - testRoom.renew(listener); - testRoom.renew(listener); - } - - @Test - public void testRenewWhileSubscribing() throws JSONException, URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - extended = spy(extended); - room = new RoomExtend(new Collection(extended, "test", "index")); - room.setRoomId("foobar"); - room.setSubscribing(true); - room.renew(listener); - room = spy(room); - room.setSubscribing(false); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - //Mock response - JSONObject result = new JSONObject(); - result.put("result", new JSONObject() - .put("channel", "channel") - .put("roomId", "42")); - //Call callback with response - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - verify(room).dequeue(); - - return null; - } - }).when(extended).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - room.renew(listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/unsubscribeTest.java b/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/unsubscribeTest.java deleted file mode 100644 index 3ec4765b..00000000 --- a/test/main/java/io/kuzzle/sdk/core/KuzzleRoom/unsubscribeTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package main.java.io.kuzzle.sdk.core.KuzzleRoom; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; -import java.util.Timer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import main.java.io.kuzzle.sdk.testUtils.RoomExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class unsubscribeTest { - private ResponseListener listener = mock(ResponseListener.class); - private JSONObject mockNotif = new JSONObject(); - private JSONObject mockResponse = new JSONObject(); - private Kuzzle k; - private RoomExtend room; - - @Before - public void setUp() throws JSONException { - mockNotif.put("type", "type") - .put("index", "index") - .put("status", 200) - .put("collection", "collection") - .put("controller", "controller") - .put("action", "action") - .put("state", "ALL") - .put("scope", "ALL") - .put("volatile", new JSONObject()) - .put("result", new JSONObject()) - .put("requestId", "42"); - mockResponse.put("result", new JSONObject().put("channel", "channel").put("roomId", "42")); - k = mock(Kuzzle.class); - when(k.getHeaders()).thenReturn(new JSONObject()); - room = new RoomExtend(new Collection(k, "test", "index")); - } - - @Test - public void testUnsubscribe() throws JSONException, URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - WebSocketClient s = mock(WebSocketClient.class); - - KuzzleExtend kuzzle = new KuzzleExtend("localhost", opts, null); - kuzzle.setState(States.CONNECTED); - kuzzle.setSocket(s); - - kuzzle = spy(kuzzle); - room = new RoomExtend(new Collection(kuzzle, "test", "index")); - room.setRoomId("42"); - room.superUnsubscribe(); - assertEquals(room.getRoomId(), null); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "realtime"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "unsubscribe"); - } - - @Test - public void testUnsubscribeWhileSubscribing() throws JSONException, URISyntaxException, InterruptedException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - extended = spy(extended); - room = new RoomExtend(new Collection(extended, "test", "index")); - room.setRoomId("foobar"); - room.setSubscribing(true); - room.superUnsubscribe(); - room = spy(room); - room.setSubscribing(false); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - //Mock response - JSONObject result = new JSONObject(); - result.put("result", new JSONObject() - .put("channel", "channel") - .put("roomId", "42")); - //Call callback with response - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(result); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - } - verify(room).dequeue(); - return null; - } - }).when(extended).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - room.renew(listener); - } - - @Test - public void testUnsubscribeWithPendingSubscriptions() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - WebSocketClient s = mock(WebSocketClient.class); - - KuzzleExtend kuzzle = new KuzzleExtend("localhost", opts, null); - kuzzle.setState(States.CONNECTED); - kuzzle.setSocket(s); - - kuzzle = spy(kuzzle); - kuzzle.getPendingSubscriptions().put("42", mock(Room.class)); - - room = new RoomExtend(new Collection(kuzzle, "test", "index")); - room.setRoomId("42"); - room.superUnsubscribe(); - - assertEquals(room.getRoomId(), null); - verify(kuzzle, never()).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testUnsubscribeException() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - extended = spy(extended); - doThrow(JSONException.class).when(extended).removeRoom(any(String.class)); - room = new RoomExtend(new Collection(extended, "test", "index")); - room.setRoomId("foobar"); - room.superUnsubscribe(); - } - - @Test - public void testUnsubscribeTask() throws URISyntaxException, JSONException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - extended = spy(extended); - - room = new RoomExtend(new Collection(extended, "test", "index")); - room.setRoomId("foobar"); - room.unsubscribeTask(new Timer(), room.getRoomId(), new JSONObject()).run(); - verify(extended).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testUnsubscribeTaskException() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - extended = spy(extended); - doThrow(JSONException.class).when(extended).getPendingSubscriptions(); - room = new RoomExtend(new Collection(extended, "test", "index")); - room.setRoomId("foobar"); - room.unsubscribeTask(new Timer(), room.getRoomId(), new JSONObject()).run(); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/listeners/KuzzleListenerTest.java b/test/main/java/io/kuzzle/sdk/listeners/KuzzleListenerTest.java deleted file mode 100644 index 6b12c6fd..00000000 --- a/test/main/java/io/kuzzle/sdk/listeners/KuzzleListenerTest.java +++ /dev/null @@ -1,148 +0,0 @@ -package main.java.io.kuzzle.sdk.listeners; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.QueryObject; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class KuzzleListenerTest { - private Kuzzle kuzzle; - private KuzzleExtend kuzzleExtend; - private Kuzzle kuzzleSpy; - private WebSocketClient s = mock(WebSocketClient.class); - private io.kuzzle.sdk.util.Event event; - private io.kuzzle.sdk.util.Event eventSpy; - - @Before - public void setUp() throws URISyntaxException { - Options options = new Options(); - options.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", options, null); - extended.setSocket(s); - kuzzle = extended; - kuzzleExtend = extended; - } - - private void mockAnswer(Event e) { - event = new io.kuzzle.sdk.util.Event(e) { - @Override - public void trigger(Object... args) { - - } - }; - eventSpy = spy(event); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - eventSpy.trigger(); - return s; - } - }).when(s).connect(); - } - - @Test - public void testCONNECTEDevent() throws URISyntaxException { - mockAnswer(Event.connected); - kuzzle.addListener(Event.connected, event); - kuzzle.connect(); - verify(eventSpy, times(1)).trigger(); - } - - @Test - public void testERRORevent() throws URISyntaxException { - mockAnswer(Event.error); - kuzzle.addListener(Event.error, event); - kuzzle.connect(); - verify(eventSpy, times(1)).trigger(); - } - - @Test - public void testDISCONNECTevent() throws URISyntaxException { - mockAnswer(Event.disconnected); - kuzzle.addListener(Event.disconnected, event); - kuzzle.connect(); - verify(eventSpy, times(1)).trigger(); - } - - @Test - public void testRECONNECTevent() throws URISyntaxException { - mockAnswer(Event.reconnected); - kuzzle.addListener(Event.reconnected, event); - kuzzle.connect(); - verify(eventSpy, times(1)).trigger(); - } - - @Test - public void testOfflineQueuePush() throws JSONException { - event = new io.kuzzle.sdk.util.Event(Event.offlineQueuePush) { - @Override - public void trigger(Object... args) { - - } - }; - eventSpy = spy(event); - kuzzleExtend.addListener(Event.offlineQueuePush, eventSpy); - - Options opts = new Options().setQueuable(true); - kuzzleExtend.setState(States.OFFLINE); - kuzzleExtend.startQueuing(); - - Kuzzle.QueryArgs args = new Kuzzle.QueryArgs(); - args.controller = "foo"; - args.action = "bar"; - kuzzleExtend.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(QueryObject.class); - verify(eventSpy).trigger(argument.capture()); - assertEquals(((QueryObject) argument.getValue()).getQuery().getString("action"), "bar"); - } - - @Test - public void testOfflineQueuePop() throws JSONException, URISyntaxException { - event = new io.kuzzle.sdk.util.Event(Event.offlineQueuePop) { - @Override - public void trigger(Object... args) { - - } - }; - eventSpy = spy(event); - kuzzleExtend.setAutoReplay(true); - kuzzleExtend.addListener(Event.offlineQueuePop, eventSpy); - mockAnswer(Event.reconnected); - - Options opts = new Options().setQueuable(true); - kuzzleExtend.setState(States.OFFLINE); - kuzzleExtend.startQueuing(); - - Kuzzle.QueryArgs args = new Kuzzle.QueryArgs(); - args.controller = "foo"; - args.action = "bar"; - kuzzleExtend.query(args, new JSONObject(), opts, mock(OnQueryDoneListener.class)); - - kuzzleExtend.connect(); - verify(eventSpy).trigger(); - } -} diff --git a/test/main/java/io/kuzzle/sdk/listeners/KuzzleSubscribeListenerTest.java b/test/main/java/io/kuzzle/sdk/listeners/KuzzleSubscribeListenerTest.java deleted file mode 100644 index b952fbbf..00000000 --- a/test/main/java/io/kuzzle/sdk/listeners/KuzzleSubscribeListenerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package main.java.io.kuzzle.sdk.listeners; - -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.SubscribeListener; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -public class KuzzleSubscribeListenerTest { - - private SubscribeListener subListener; - private ResponseListener callback; - private JSONObject json = new JSONObject(); - - @Before - public void setUp() { - subListener = new SubscribeListener(); - callback = spy(new ResponseListener() { - @Override - public void onSuccess(Room response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }); - } - - @Test - public void testOnDoneError() { - subListener.onDone(callback); - subListener.done(json, null); - verify(callback).onError(any(JSONObject.class)); - } - - @Test - public void testOnDoneSuccess() { - subListener.onDone(callback); - subListener.done(null, mock(Room.class)); - verify(callback).onSuccess(any(Room.class)); - } - - @Test - public void testPostOnDoneError() { - subListener.done(json, null); - subListener.onDone(callback); - verify(callback).onError(any(JSONObject.class)); - } - - @Test - public void testPostOnDoneSuccess() { - subListener.done(null, mock(Room.class)); - subListener.onDone(callback); - verify(callback).onSuccess(any(Room.class)); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/responses/SearchResultTest.java b/test/main/java/io/kuzzle/sdk/responses/SearchResultTest.java deleted file mode 100644 index 37358ec8..00000000 --- a/test/main/java/io/kuzzle/sdk/responses/SearchResultTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package main.java.io.kuzzle.sdk.responses; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import java.net.URISyntaxException; -import java.util.ArrayList; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Document; -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.responses.SearchResult; -import io.kuzzle.sdk.state.States; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class SearchResultTest { - private Collection collection; - private Kuzzle kuzzle; - private ResponseListener listener; - private long total; - private ArrayList documents; - private Options options; - private String scrollId; - private String scroll; - - @Before - public void setUp() throws URISyntaxException { - options = new Options(); - options.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", options, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - collection = new Collection(kuzzle, "test", "index"); - listener = mock(ResponseListener.class); - total = (long) 42; - documents = new ArrayList<>(); - scrollId = "someScrollId"; - scroll = "someScroll"; - try { - documents.add(new Document(collection, "foo", new JSONObject().put("name", "John").put("age", 42))); - documents.add(new Document(collection, "bar", new JSONObject().put("name", "Michael").put("age", 36))); - } catch(JSONException e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkConstructorArguments() { - SearchResult searchResult = new SearchResult(collection, total, documents, null, options, null); - assertEquals(searchResult.getCollection(), collection); - assertEquals(searchResult.getTotal(), total); - assertEquals(searchResult.getDocuments(), documents); - assertEquals(searchResult.getAggregations(), null); - assertEquals(searchResult.getOptions(), options); - assertEquals(searchResult.getFilters(), null); - assertEquals(searchResult.getFetchedDocument(), (long) 2); - } - - @Test - public void fetchNextBySearchAfter() throws JSONException { - Options localOptions = new Options(options); - localOptions - .setSize((long) 2); - - JSONObject filters = new JSONObject() - .put("sort", new JSONArray() - .put(new JSONObject() - .put("age", "desc") - ) - .put(new JSONObject() - .put("name", "asc") - ) - ); - - collection = spy(collection); - SearchResult searchResult = new SearchResult(collection, total, documents, null, localOptions, filters); - - searchResult.fetchNext(listener); - - JSONObject expectedFilters = new JSONObject() - .put("search_after", new JSONArray() - .put(36) - .put("Michael") - ) - .put("sort", new JSONArray() - .put(new JSONObject() - .put("age", "desc") - ) - .put(new JSONObject() - .put("name", "asc") - ) - ); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(collection).search((JSONObject) argument.capture(), any(Options.class), eq(listener)); - - assertEquals(argument.getValue().toString(), expectedFilters.toString()); - } - - @Test - public void fetchNextByScroll() throws JSONException { - Options localOptions = new Options(options); - localOptions - .setScroll(scroll) - .setScrollId(scrollId); - - collection = spy(collection); - SearchResult searchResult = new SearchResult(collection, total, documents, null, localOptions, null); - - searchResult.fetchNext(listener); - - verify(collection).scroll(eq(scrollId), any(Options.class), any(JSONObject.class), eq(listener)); - } - - @Test - public void fetchNextBySearch() throws JSONException { - Options localOptions = new Options(options); - localOptions - .setFrom((long) 0) - .setSize((long) 2); - - collection = spy(collection); - SearchResult searchResult = new SearchResult(collection, total, documents, null, localOptions, new JSONObject()); - - searchResult.fetchNext(listener); - - verify(collection).search(any(JSONObject.class), any(Options.class), eq(listener)); - } - - @Test(expected = RuntimeException.class) - public void fetchNextOnError() throws JSONException { - Options localOptions = new Options(options); - - collection = spy(collection); - SearchResult searchResult = new SearchResult(collection, total, documents, null, localOptions, new JSONObject()); - - searchResult.fetchNext(listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleProfileTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleProfileTest.java deleted file mode 100644 index 483f9e07..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleProfileTest.java +++ /dev/null @@ -1,214 +0,0 @@ -package main.java.io.kuzzle.sdk.security; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Profile; -import io.kuzzle.sdk.security.Security; - -import java.util.Map; - -import static org.junit.Assert.assertFalse; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class KuzzleProfileTest { - private Kuzzle kuzzle; - private Profile stubProfile; - - @Before - public void setUp() throws JSONException { - kuzzle = mock(Kuzzle.class); - kuzzle.security = new Security(kuzzle); - stubProfile = new Profile(kuzzle, "foo", null, null); - } - - @Test - public void testConstructorNoContent() throws JSONException { - Profile profile = new Profile(kuzzle, "foo", null, null); - assertEquals(profile.id, "foo"); - assertEquals(profile.getPolicies().length, 0); - assertThat(profile.content, instanceOf(JSONObject.class)); - assertEquals(profile.content.length(), 0); - } - - @Test - public void testConstructorContentWithIDs() throws JSONException { - JSONObject content = new JSONObject( - "{" + - "\"policies\": [{\"roleId\": \"foo\"}, {\"roleId\": \"bar\"}, {\"roleId\": \"baz\"}]" + - "}" - ); - Profile profile = new Profile(kuzzle, "foo", content, null); - assertEquals(profile.id, "foo"); - assertEquals(profile.getPolicies().length, 3); - assertEquals(profile.getPolicies()[2].getString("roleId"), "baz"); - assertThat(profile.content, instanceOf(JSONObject.class)); - assertEquals(profile.content.length(), 0); - } - - @Test - public void testConstructorContentWithRoles() throws JSONException { - JSONObject content = new JSONObject( - "{" + - "\"policies\": [" + - "{\"roleId\": \"foo\"}, " + - "{\"roleId\": \"bar\"}, " + - "{\"roleId\": \"baz\"}" + - "]" + - "}" - ); - Profile profile = new Profile(kuzzle, "foo", content, null); - assertEquals(profile.id, "foo"); - assertEquals(profile.getPolicies().length, 3); - assertEquals(profile.getPolicies()[2].getString("roleId"), "baz"); - assertThat(profile.content, instanceOf(JSONObject.class)); - assertEquals(profile.content.length(), 0); - } - - @Test - public void testConstructorMeta() throws JSONException { - JSONObject meta = new JSONObject() - .put("createdAt", "0123456789") - .put("author", "-1"); - Profile profile = new Profile(kuzzle, "foo", null, meta); - assertEquals(profile.id, "foo"); - assertEquals(profile.getMeta().length(), 2); - assertEquals(profile.getMeta().getString("createdAt"), "0123456789"); - assertEquals(profile.getMeta().getString("author"), "-1"); - assertThat(profile.meta, instanceOf(JSONObject.class)); - } - - @Test - public void testAddPolicyObject() throws JSONException { - stubProfile.addPolicy(new JSONObject().put("roleId", "some role")); - assertEquals(stubProfile.getPolicies().length, 1); - assertEquals(stubProfile.getPolicies()[0].getString("roleId"), "some role"); - } - - @Test(expected = IllegalArgumentException.class) - public void testAddNullPolicyObject() throws JSONException { - stubProfile.addPolicy(new JSONObject().put("roleId", (Object)null)); - doThrow(IllegalArgumentException.class).when(stubProfile).addPolicy(any(JSONObject.class)); - } - - @Test - public void testAddPolicyID() throws JSONException { - stubProfile.addPolicy("another role"); - assertEquals(stubProfile.getPolicies().length, 1); - assertEquals(stubProfile.getPolicies()[0].getString("roleId"), "another role"); - } - - @Test(expected = IllegalArgumentException.class) - public void testSaveNoRole() throws JSONException { - stubProfile.save(); - } - - @Test - public void testSaveNoListener() throws JSONException { - stubProfile.addPolicy("baz"); - stubProfile.save(); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createOrReplaceProfile"); - } - - @Test - public void testSave() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject()); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubProfile.addPolicy("baz"); - stubProfile.save(new ResponseListener() { - @Override - public void onSuccess(Profile response) { - assertEquals(response, stubProfile); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - stubProfile.save(mock(Options.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createOrReplaceProfile"); - } - - @Test - public void testSetPoliciesObjectList() throws JSONException { - JSONObject[] policies = new JSONObject[]{ - new JSONObject().put("roleId", "bar"), - new JSONObject().put("roleId", "baz"), - new JSONObject().put("roleId", "qux") - }; - - stubProfile.addPolicy("foo"); - stubProfile.setPolicies(policies); - assertEquals(stubProfile.getPolicies().length, 3); - assertEquals(stubProfile.getPolicies()[0].getString("roleId"), "bar"); - assertEquals(stubProfile.getPolicies()[1].getString("roleId"), "baz"); - assertEquals(stubProfile.getPolicies()[2].getString("roleId"), "qux"); - } - - @Test - public void testSetRolesIDs() throws JSONException { - String[] policies = {"bar", "baz", "qux"}; - - stubProfile.addPolicy("foo"); - assertEquals(stubProfile.getPolicies().length, 1); - - stubProfile.setPolicies(policies); - assertEquals(stubProfile.getPolicies().length, 3); - assertEquals(stubProfile.getPolicies()[0].getString("roleId"), "bar"); - assertEquals(stubProfile.getPolicies()[1].getString("roleId"), "baz"); - assertEquals(stubProfile.getPolicies()[2].getString("roleId"), "qux"); - - stubProfile.addPolicy("foo"); - assertEquals(stubProfile.getPolicies().length, 4); - assertEquals(stubProfile.getPolicies()[3].getString("roleId"), "foo"); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetBadPolicies() throws JSONException { - stubProfile.setPolicies(new JSONObject[]{new JSONObject().put("bad", "policy")}); - - doThrow(IllegalArgumentException.class).when(stubProfile).setPolicies(any(JSONObject[].class)); - } - - @Test - public void testSerializeWithNoPolicies() throws JSONException { - assertFalse(stubProfile.serialize().getJSONObject("body").has("policies")); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleRoleTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleRoleTest.java deleted file mode 100644 index b62dabfa..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleRoleTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package main.java.io.kuzzle.sdk.security; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Role; -import io.kuzzle.sdk.security.Security; - -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class KuzzleRoleTest { - private Kuzzle kuzzle; - private Role stubRole; - - @Before - public void setUp() throws JSONException { - kuzzle = mock(Kuzzle.class); - kuzzle.security = new Security(kuzzle); - stubRole = new Role(kuzzle, "foo", null, null); - } - - @Test - public void testConstructorMeta() throws JSONException { - JSONObject meta = new JSONObject() - .put("createdAt", "0123456789") - .put("author", "-1"); - Role role = new Role(kuzzle, "foo", null, meta); - assertEquals(role.id, "foo"); - assertEquals(role.getMeta().length(), 2); - assertEquals(role.getMeta().getString("createdAt"), "0123456789"); - assertEquals(role.getMeta().getString("author"), "-1"); - assertThat(role.meta, instanceOf(JSONObject.class)); - } - - @Test - public void testSaveNoListener() throws JSONException { - stubRole.save(); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createOrReplaceRole"); - } - - @Test - public void testSave() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject()); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubRole.save(new ResponseListener() { - @Override - public void onSuccess(Role response) { - assertEquals(response, stubRole); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - stubRole.save(mock(Options.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createOrReplaceRole"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/AbstractKuzzleSecurityDocumentTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/AbstractKuzzleSecurityDocumentTest.java deleted file mode 100644 index 0671e1d6..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/AbstractKuzzleSecurityDocumentTest.java +++ /dev/null @@ -1,186 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.AbstractSecurityDocument; -import io.kuzzle.sdk.security.Role; -import io.kuzzle.sdk.security.Security; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class AbstractKuzzleSecurityDocumentTest { - private Kuzzle kuzzle; - private Role stubRole; - private ResponseListener listener; - - @Before - public void setUp() throws JSONException { - kuzzle = mock(Kuzzle.class); - kuzzle.security = new Security(kuzzle); - listener = mock(ResponseListener.class); - stubRole = new Role(kuzzle, "foo", new JSONObject("{\"foo\":\"bar\"}"), null); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetContentNoContent() throws JSONException { - stubRole.setContent(null); - } - - @Test - public void testSetContent() throws JSONException { - JSONObject content = new JSONObject().put("foo", "bar"); - assertEquals(stubRole.setContent(content), stubRole); - assertThat(stubRole.content, not(equalTo(content))); - assertEquals(stubRole.content.toString(), content.toString()); - } - - @Test - public void testSerialize() throws JSONException { - JSONObject - serialized, - content = new JSONObject().put("bar", "qux"); - - stubRole.setContent(content); - - serialized = stubRole.serialize(); - - assertEquals(serialized.getString("_id"), stubRole.id); - assertEquals(serialized.getJSONObject("body").toString(), content.toString()); - } - - @Test - public void testDeleteNoListener() throws JSONException { - stubRole.delete(); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteRole"); - } - - @Test - public void testDelete() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject content = new JSONObject("{\"result\": { \"_id\": \"foo\", \"_source\": {} }}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(content); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubRole.delete(new ResponseListener() { - @Override - public void onSuccess(String response) { - assertEquals(response, "foo"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - stubRole.delete(); - stubRole.delete(mock(Options.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - verify(kuzzle, times(2)).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class)); - - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteRole"); - } - - @Test(expected = RuntimeException.class) - public void testDeleteInvalidJSON() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject content = new JSONObject(); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(content); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubRole.delete(listener); - } - - @Test - public void testUpdate() throws JSONException { - JSONObject content = new JSONObject(); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject content = new JSONObject("{\"result\": { \"_id\": \"foo\", \"_source\": {} }}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(content); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubRole.update(content, new ResponseListener() { - @Override - public void onSuccess(AbstractSecurityDocument response) { - assertEquals(response.getId(), "foo"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - stubRole.update(content); - stubRole.update(content, mock(Options.class)); - verify(kuzzle, times(2)).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class)); - verify(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } - - @Test(expected = RuntimeException.class) - public void testUpdateInvalidJSON() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject content = new JSONObject(); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(content); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubRole.update(new JSONObject(), listener); - } - - @Test - public void testGetContent() throws JSONException { - assertTrue(stubRole.getContent().getString("foo").equals("bar")); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createCredentialsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createCredentialsTest.java deleted file mode 100644 index 9c4c4b88..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createCredentialsTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Security; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class createCredentialsTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - private JSONObject credentials = mock(JSONObject.class); - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testCreateCredentialsException() throws JSONException { - listener = spy(listener); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.createCredentials("strategy", "kuid", credentials, null, listener); - } - - @Test(expected = RuntimeException.class) - public void testCreateCredentialsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.createCredentials("strategy", "kuid", credentials, null, listener); - } - - @Test - public void testCreateCredentials() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzleSecurity.createCredentials("strategy", "kuid", credentials) - .createCredentials("strategy", "kuid", credentials, mock(Options.class)) - .createCredentials("strategy", "kuid", credentials, mock(ResponseListener.class)) - .createCredentials("strategy", "kuid", credentials, mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(4)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "createCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createProfileTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createProfileTest.java deleted file mode 100644 index 15b02d6e..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createProfileTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Profile; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class createProfileTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateProfileNoID() throws JSONException { - kuzzleSecurity.createProfile(null, new JSONObject[0]); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateProfileNoContent() throws JSONException { - kuzzleSecurity.createProfile("foo", null); - } - - @Test - public void testCreateProfileNoListener() throws JSONException { - kuzzleSecurity.createProfile("foo", new JSONObject[0], new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createProfile"); - } - - @Test - public void testCreateProfileReplaceIfExists() throws JSONException { - Options options = new Options().setReplaceIfExist(true); - - kuzzleSecurity.createProfile("foo", new JSONObject[0], options); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createOrReplaceProfile"); - } - - @Test - public void testCreateProfileValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {" + - "\"indexes\": {}" + - "}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.createProfile("foobar", new JSONObject[0], new ResponseListener() { - @Override - public void onSuccess(Profile response) { - assertEquals(response.id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createProfile"); - } - - @Test(expected = RuntimeException.class) - public void testCreateProfileBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.createProfile("foobar", new JSONObject[0], listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createRestrictedUserTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createRestrictedUserTest.java deleted file mode 100644 index 14723542..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createRestrictedUserTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.security.User; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class createRestrictedUserTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateRestrictedUserNoID() throws JSONException { - kuzzleSecurity.createRestrictedUser(null, new JSONObject()); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateRestrictedWithProfileIds() throws JSONException { - kuzzleSecurity.createRestrictedUser("some_id", new JSONObject().put("profileIds", new JSONArray())); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateRestrictedUserNoContent() throws JSONException { - kuzzleSecurity.createRestrictedUser("foo", null); - } - - @Test - public void testCreateRestrictedUserNoListener() throws JSONException { - kuzzleSecurity.createRestrictedUser("foo", new JSONObject(), new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "createRestrictedUser"); - } - - @Test - public void testCreateRestrictedUserReplaceIfExists() throws JSONException { - Options options = new Options().setReplaceIfExist(true); - - kuzzleSecurity.createRestrictedUser("foo", new JSONObject(), options); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "createRestrictedUser"); - } - - @Test - public void testCreateRestrictedUserValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {" + - "\"indexes\": {}" + - "}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.createRestrictedUser("foobar", new JSONObject(), new ResponseListener() { - @Override - public void onSuccess(User response) { - assertEquals(response.id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "createRestrictedUser"); - } - - @Test(expected = RuntimeException.class) - public void testCreateRestrictedUserBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.createRestrictedUser("foobar", new JSONObject(), listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createRoleTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createRoleTest.java deleted file mode 100644 index a45c6e91..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createRoleTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Role; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class createRoleTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateRoleNoID() throws JSONException { - kuzzleSecurity.createRole(null, new JSONObject()); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateRoleNoContent() throws JSONException { - kuzzleSecurity.createRole("foo", null); - } - - @Test - public void testCreateRoleNoListener() throws JSONException { - kuzzleSecurity.createRole("foo", new JSONObject(), new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createRole"); - } - - @Test - public void testCreateRoleReplaceIfExists() throws JSONException { - Options options = new Options().setReplaceIfExist(true); - - kuzzleSecurity.createRole("foo", new JSONObject(), options); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createOrReplaceRole"); - } - - @Test - public void testCreateRoleValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {" + - "\"indexes\": {}" + - "}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.createRole("foobar", new JSONObject(), new ResponseListener() { - @Override - public void onSuccess(Role response) { - assertEquals(response.id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createRole"); - } - - @Test(expected = RuntimeException.class) - public void testCreateRoleBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.createRole("foobar", new JSONObject(), listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createUserTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createUserTest.java deleted file mode 100644 index 2388e24a..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/createUserTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.security.User; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class createUserTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateUserNoID() throws JSONException { - kuzzleSecurity.createUser(null, new JSONObject()); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateUserNoContent() throws JSONException { - kuzzleSecurity.createUser("foo", null); - } - - @Test - public void testCreateUserNoListener() throws JSONException { - kuzzleSecurity.createUser("foo", new JSONObject(), new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createUser"); - } - - @Test - public void testCreateUserValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {" + - "\"indexes\": {}" + - "}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.createUser("foobar", new JSONObject(), new ResponseListener() { - @Override - public void onSuccess(User response) { - assertEquals(response.id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createUser"); - } - - @Test(expected = RuntimeException.class) - public void testCreateUserBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.createUser("foobar", new JSONObject(), listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteCredentialsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteCredentialsTest.java deleted file mode 100644 index c15df040..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteCredentialsTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Security; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class deleteCredentialsTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testDeleteCredentialsException() throws JSONException { - listener = spy(listener); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.deleteCredentials("strategy", "kuid", null, listener); - } - - @Test(expected = RuntimeException.class) - public void testDeleteCredentialsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.deleteCredentials("strategy", "kuid", null, listener); - } - - @Test - public void testDeleteCredentials() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzleSecurity.deleteCredentials("strategy", "kuid") - .deleteCredentials("strategy", "kuid", mock(Options.class)) - .deleteCredentials("strategy", "kuid", mock(ResponseListener.class)) - .deleteCredentials("strategy", "kuid", mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(4)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "deleteCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteProfileTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteProfileTest.java deleted file mode 100644 index 8e45bae6..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteProfileTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class deleteProfileTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test - public void testDeleteProfileNoListener() throws JSONException { - kuzzleSecurity.deleteProfile("foo", new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteProfile"); - } - - @Test - public void testDeleteProfileValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.deleteProfile("foobar", new ResponseListener() { - @Override - public void onSuccess(String response) { - assertEquals(response, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteProfile"); - } - - @Test(expected = RuntimeException.class) - public void testDeleteProfileBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.deleteProfile("foobar", new Options(), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testDeleteProfileNoID() throws JSONException { - kuzzleSecurity.deleteProfile(null); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteRoleTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteRoleTest.java deleted file mode 100644 index c7860035..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteRoleTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class deleteRoleTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testDeleteRoleNoID() throws JSONException { - kuzzleSecurity.deleteRole(null); - } - - @Test - public void testDeleteRoleNoListener() throws JSONException { - kuzzleSecurity.deleteRole("foo", new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteRole"); - } - - @Test - public void testDeleteRoleValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.deleteRole("foobar", new ResponseListener() { - @Override - public void onSuccess(String response) { - assertEquals(response, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteRole"); - } - - @Test(expected = RuntimeException.class) - public void testDeleteRoleBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.deleteRole("foobar", new Options(), listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteUserTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteUserTest.java deleted file mode 100644 index 62861039..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/deleteUserTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class deleteUserTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testDeleteUserNoID() throws JSONException { - kuzzleSecurity.deleteUser(null); - } - - @Test - public void testDeleteUserNoListener() throws JSONException { - kuzzleSecurity.deleteUser("foo", new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteUser"); - } - - @Test - public void testDeleteUserValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.deleteUser("foobar", new ResponseListener() { - @Override - public void onSuccess(String response) { - assertEquals(response, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "deleteUser"); - } - - @Test(expected = RuntimeException.class) - public void testDeleteUserBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.deleteUser("foobar", new Options(), listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/factoriesTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/factoriesTest.java deleted file mode 100644 index ee6f341c..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/factoriesTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Profile; -import io.kuzzle.sdk.security.Role; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.security.User; - -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; - -public class factoriesTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test - public void testRoleFactory() throws JSONException { - assertThat(kuzzleSecurity.role("id"), instanceOf(Role.class)); - assertThat(kuzzleSecurity.role("id", new JSONObject()), instanceOf(Role.class)); - } - - @Test - public void testProfileFactory() throws JSONException { - assertThat(kuzzleSecurity.profile("id"), instanceOf(Profile.class)); - assertThat(kuzzleSecurity.profile("id", new JSONObject()), instanceOf(Profile.class)); - } - - @Test - public void testUserFactory() throws JSONException { - assertThat(kuzzleSecurity.user("id"), instanceOf(User.class)); - assertThat(kuzzleSecurity.user("id", new JSONObject()), instanceOf(User.class)); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getAllCredentialFieldsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getAllCredentialFieldsTest.java deleted file mode 100644 index 67a6740f..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getAllCredentialFieldsTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Security; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class getAllCredentialFieldsTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = IllegalArgumentException.class) - public void testNullListener() { - kuzzleSecurity.getAllCredentialFields(null, null); - } - - @Test(expected = RuntimeException.class) - public void testGetAllCredentialsFieldsException() throws JSONException { - listener = spy(listener); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getAllCredentialFields(listener); - } - - @Test(expected = RuntimeException.class) - public void testGetAllCredentialsFieldsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getAllCredentialFields(listener); - } - - @Test - public void testGetAllCredentialsFields() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzleSecurity.getAllCredentialFields(listener); - kuzzleSecurity.getAllCredentialFields(mock(Options.class), listener); - - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "getAllCredentialFields"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getCredentialFieldsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getCredentialFieldsTest.java deleted file mode 100644 index 168566c8..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getCredentialFieldsTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Security; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class getCredentialFieldsTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testGetCredentialsFieldsException() throws JSONException { - listener = spy(listener); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getCredentialFields("strategy", null, listener); - } - - @Test(expected = RuntimeException.class) - public void testGetCredentialsFieldsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getCredentialFields("strategy", null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testListenerNull() { - kuzzleSecurity.getCredentialFields("strategy", null, null); - } - - @Test - public void testGetCredentialsFields() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("hits", new JSONArray()))); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzleSecurity.getCredentialFields("strategy", mock(ResponseListener.class)); - kuzzleSecurity.getCredentialFields("strategy", mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "getCredentialFields"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getCredentialsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getCredentialsTest.java deleted file mode 100644 index e5b219b9..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getCredentialsTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Security; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class getCredentialsTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testGetCredentialsException() throws JSONException { - listener = spy(listener); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getCredentials("strategy", "kuid", null, listener); - } - - @Test(expected = RuntimeException.class) - public void testGetCredentialsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getCredentials("strategy", "kuid", null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testListenerNull() { - kuzzleSecurity.getCredentials("strategy", null, null); - } - - @Test - public void testGetCredentials() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzleSecurity.getCredentials("strategy", "kuid", mock(ResponseListener.class)); - kuzzleSecurity.getCredentials("strategy", "kuid", mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "getCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getProfileTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getProfileTest.java deleted file mode 100644 index 321f396f..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getProfileTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; - -public class getProfileTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - @Test(expected = IllegalArgumentException.class) - public void testGetProfileNoID() throws JSONException { - kuzzleSecurity.fetchProfile(null, new Options(), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetProfileNoListener() throws JSONException { - kuzzleSecurity.fetchProfile("foo", null); - } - - @Test(expected = RuntimeException.class) - public void testGetProfileBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchProfile("foobar", listener); - } - - @Test - public void testGetProfileGoodFullResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\":{\"_id\":\"foobar\",\"_source\":{\"policies\":[{\"roleId\":\"baz\",\"restrictedTo\":[{\"index\":\"qux\"}],\"allowInternalIndex\":true}]},\"_meta\":{}}}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchProfile("foobar", listener); - } - - @Test - public void testGetProfileGoodMinimalResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\":{\"_id\":\"foobar\",\"_source\":{\"policies\":[{\"roleId\":\"baz\"}]},\"_meta\":{}}}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchProfile("foobar", listener); - } - - @Test - public void testGetProfileGoodWithRestrictedToResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\":{\"_id\":\"foobar\",\"_source\":{\"policies\":[{\"roleId\":\"baz\"}],\"restrictedTo\":[{\"index\":\"qux\"}]},\"_meta\":{}}}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchProfile("foobar", listener); - } - - @Test - public void testGetProfileGoodWithAllowInternalIndexResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\":{\"_id\":\"foobar\",\"_source\":{\"policies\":[{\"roleId\":\"baz\"}],\"allowInternalIndex\":true},\"_meta\":{}}}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchProfile("foobar", listener); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getRoleTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getRoleTest.java deleted file mode 100644 index c5535d67..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getRoleTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Role; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class getRoleTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetRoleNoID() { - kuzzleSecurity.fetchRole(null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetRoleNoListener() { - kuzzleSecurity.fetchRole("foobar", null); - } - - @Test - public void testGetRoleValid() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {" + - "\"indexes\": {}" + - "}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchRole("foobar", null, new ResponseListener() { - @Override - public void onSuccess(Role response) { - assertEquals(response.id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } - catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getRole"); - } - - @Test(expected = RuntimeException.class) - public void testGetRoleInvalid() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.fetchRole("foobar", null, listener); - } - - @Test(expected = RuntimeException.class) - public void testGetRoleInvalidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchRole("foobar", null, listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getUserRightsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getUserRightsTest.java deleted file mode 100644 index a7993d7b..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getUserRightsTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class getUserRightsTest { - - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testIllegalUserId() { - kuzzleSecurity.getUserRights(null, mock(ResponseListener.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testIllegalCallback() { - kuzzleSecurity.getUserRights("id", null); - } - - @Test(expected = RuntimeException.class) - public void testQueryException() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getUserRights("id", listener); - } - - @Test(expected = RuntimeException.class) - public void testException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getUserRights("id", listener); - } - - @Test - public void testGetUserRights() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject() - .put("result", new JSONObject() - .put("hits", new JSONArray())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.getUserRights("id", mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getUserRights"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getUserTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getUserTest.java deleted file mode 100644 index 5697a1aa..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/getUserTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.security.User; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class getUserTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetUserNoID() throws JSONException { - kuzzleSecurity.fetchUser(null, new Options(), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetUserNoListener() throws JSONException { - kuzzleSecurity.fetchUser("foo", null); - } - - @Test - public void testGetUserValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchUser("foobar", new ResponseListener() { - @Override - public void onSuccess(User response) { - assertEquals(response.id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getUser"); - } - - @Test(expected = RuntimeException.class) - public void testGetUserBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.fetchUser("foobar", listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/hasCredentialsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/hasCredentialsTest.java deleted file mode 100644 index eb389f22..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/hasCredentialsTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Security; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class hasCredentialsTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testHasCredentialsException() throws JSONException { - listener = spy(listener); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.hasCredentials("strategy", "kuid", null, listener); - } - - @Test(expected = RuntimeException.class) - public void testHasCredentialsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.hasCredentials("strategy", "kuid", null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testListenerNull() { - kuzzleSecurity.hasCredentials("strategy", null, null); - } - - @Test - public void testHasCredentials() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", true)); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzleSecurity.hasCredentials("strategy", "kuid", mock(ResponseListener.class)); - kuzzleSecurity.hasCredentials("strategy", "kuid", mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "hasCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/isActionAllowedTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/isActionAllowedTest.java deleted file mode 100644 index ffa98ab9..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/isActionAllowedTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.enums.Policies; -import io.kuzzle.sdk.security.Security; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; - -public class isActionAllowedTest { - private Security kuzzleSecurity; - private JSONObject[] policies; - - private JSONObject addProperties(final String ctrl, final String action, final String idx, final String collection, final String value) throws JSONException { - return new JSONObject() - .put("controller", ctrl) - .put("action", action) - .put("index", idx) - .put("collection", collection) - .put("value", value); - } - - @Before - public void setUp() throws JSONException { - Kuzzle kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - policies = new JSONObject[]{ - addProperties("document", "get", "*", "*", Policies.allowed.toString()), - addProperties("document", "count", "*", "*", Policies.allowed.toString()), - addProperties("document", "search", "*", "*", Policies.allowed.toString()), - addProperties("document", "*", "index1", "collection1", Policies.allowed.toString()), - addProperties("document", "*", "index1", "collection2", Policies.allowed.toString()), - addProperties("document", "update", "*", "*", Policies.allowed.toString()), - addProperties("document", "create", "*", "*", Policies.allowed.toString()), - addProperties("document", "createOrReplace", "*", "*", Policies.allowed.toString()), - addProperties("document", "delete", "*", "*", Policies.conditional.toString()), - addProperties("realtime", "publish", "index2", "*", Policies.allowed.toString()), - addProperties("security", "searchUsers", "*", "*", Policies.allowed.toString()), - addProperties("security", "updateUser", "*", "*", Policies.conditional.toString()) - }; - } - - @Test(expected = IllegalArgumentException.class) - public void testNullPolicies() { - kuzzleSecurity.isActionAllowed(null, "ctrl", "action"); - } - - @Test(expected = IllegalArgumentException.class) - public void testNullController() { - kuzzleSecurity.isActionAllowed(policies, null, "action"); - } - - @Test(expected = IllegalArgumentException.class) - public void testNullAction() { - kuzzleSecurity.isActionAllowed(policies, "ctrl", null); - } - - @Test(expected = IllegalArgumentException.class) - public void testEmptyController() { - kuzzleSecurity.isActionAllowed(policies, "", null); - } - - @Test(expected = IllegalArgumentException.class) - public void testEmptyAction() { - kuzzleSecurity.isActionAllowed(policies, "ctrl", ""); - } - - @Test - public void testControllerActionAllowed() { - assertEquals(Policies.allowed, kuzzleSecurity.isActionAllowed(policies, "document", "get")); - } - - @Test - public void testControllerActionIndexAllowed() { - assertEquals(Policies.allowed, kuzzleSecurity.isActionAllowed(policies, "document", "count", "myIndex")); - } - - @Test - public void testControllerActionIndexCollectionAllowed() { - assertEquals(Policies.allowed, kuzzleSecurity.isActionAllowed(policies, "document", "search", "index1", "collection1")); - } - - @Test - public void testControllerActionIndexCollection2Allowed() { - assertEquals(Policies.allowed, kuzzleSecurity.isActionAllowed(policies, "document", "search", "index1", "collection2")); - } - - @Test - public void testControllerActionDenied() { - assertEquals(Policies.denied, kuzzleSecurity.isActionAllowed(policies, "document", "replace")); - } - - @Test - public void testControllerActionIndexDenied() { - assertEquals(Policies.denied, kuzzleSecurity.isActionAllowed(policies, "index", "list", "index2")); - } - - @Test - public void testControllerActionConditional() { - assertEquals(Policies.conditional, kuzzleSecurity.isActionAllowed(policies, "security", "updateUser")); - } - - @Test - public void testControllerActionIndexCollectionConditional() { - assertEquals(Policies.conditional, kuzzleSecurity.isActionAllowed(policies, "document", "delete", "index2", "collection1")); - } - - @Test(expected = RuntimeException.class) - public void testJsonException() throws JSONException { - JSONObject spy = spy(policies[0]); - doThrow(JSONException.class).when(spy.getString(any(String.class))); - kuzzleSecurity.isActionAllowed(policies, "document", "delete", "index1", "collection1"); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/replaceUserTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/replaceUserTest.java deleted file mode 100644 index 956fbf19..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/replaceUserTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.security.User; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class replaceUserTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - private JSONObject content; - - @Before - public void setUp() throws JSONException { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - content = new JSONObject() - .put("foo", "bar"); - } - - @Test - public void testReplaceUserNoListener() throws JSONException { - kuzzleSecurity.replaceUser("foo", content, new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "replaceUser"); - } - - @Test - public void testReplaceUserValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foo\"," + - "\"_source\": {}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.replaceUser("foo", content, new ResponseListener() { - @Override - public void onSuccess(User response) { - assertEquals(response.getId(), "foo"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "replaceUser"); - } - - @Test(expected = RuntimeException.class) - public void testReplaceUserBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.replaceUser("foo", content, new Options(), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testReplaceUserNoID() throws JSONException { - kuzzleSecurity.replaceUser(null, content); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/scrollProfilesTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/scrollProfilesTest.java deleted file mode 100644 index 91d35b76..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/scrollProfilesTest.java +++ /dev/null @@ -1,181 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.responses.SecurityDocumentList; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.Scroll; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class scrollProfilesTest { - private Kuzzle kuzzle; - private Security security; - private ResponseListener listener; - private Options options; - private Scroll scroll; - private String scrollId; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - security = new Security(kuzzle); - listener = mock(ResponseListener.class); - options = mock(Options.class); - scroll = new Scroll(); - scrollId = "f00ba5"; - } - - @Test(expected = IllegalArgumentException.class) - public void testScrollProfilesNoScrollId() throws JSONException { - security.scrollProfiles(scroll, null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testScrollProfilesIllegalListener() throws JSONException { - scroll.setScrollId(scrollId); - security.scrollProfiles(scroll, null); - } - - @Test - public void checkSignaturesVariants() throws JSONException { - security = spy(security); - scroll.setScrollId(scrollId); - - security.scrollProfiles(scroll, listener); - verify(security).scrollProfiles(eq(scroll), eq(listener)); - - security.scrollProfiles(scroll, options, listener); - verify(security).scrollProfiles(eq(scroll), eq(options), eq(listener)); - } - - @Test(expected = RuntimeException.class) - public void testScrollProfilesQueryException() throws JSONException { - scroll.setScrollId(scrollId); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - security.scrollProfiles(scroll, listener); - } - - @Test(expected = RuntimeException.class) - public void testScrollProfilesException() throws JSONException { - scroll.setScrollId(scrollId); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(Integer.class)); - security.scrollProfiles(scroll, listener); - } - - @Test - public void testScrollProfiles() throws JSONException { - scroll.setScrollId("f00ba5"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\": {\n" + - " \"_shards\": {\n" + - " \"failed\": 0,\n" + - " \"successful\": 5,\n" + - " \"total\": 5\n" + - " },\n" + - " \"hits\": [\n" + - " {\n" + - " \"_id\": \"AVJAwyDMZAGQHg9Dhfw2\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073821,\n" + - " \"lon\": 3.9130721\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"customer\"\n" + - " },\n" + - " \"_meta\": {},\n" + - " \"_type\": \"users\"\n" + - " },\n" + - " {\n" + - " \"_id\": \"AVJAwyOvZAGQHg9Dhfw3\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073683,\n" + - " \"lon\": 3.8999983\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"cab\"\n" + - " },\n" + - " \"_meta\": {},\n" + - " \"_type\": \"users\"\n" + - " }\n" + - " ],\n" + - " \"max_score\": 1,\n" + - " \"timed_out\": false,\n" + - " \"took\": 307,\n" + - " \"total\": 2\n" + - " }" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - security.scrollProfiles(scroll, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList result) { - assertEquals(result.getTotal(), 2); - assertEquals(result.getDocuments().get(1).getId(), "AVJAwyOvZAGQHg9Dhfw3"); - } - - @Override - public void onError(JSONObject error) { - } - }); - security.scrollProfiles(scroll, mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "scrollProfiles"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/scrollUsersTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/scrollUsersTest.java deleted file mode 100644 index bd368056..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/scrollUsersTest.java +++ /dev/null @@ -1,181 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URISyntaxException; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.enums.Mode; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.responses.SecurityDocumentList; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.Scroll; -import main.java.io.kuzzle.sdk.testUtils.KuzzleExtend; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class scrollUsersTest { - private Kuzzle kuzzle; - private Security security; - private ResponseListener listener; - private Options options; - private Scroll scroll; - private String scrollId; - - @Before - public void setUp() throws URISyntaxException { - Options opts = new Options(); - opts.setConnect(Mode.MANUAL); - KuzzleExtend extended = new KuzzleExtend("localhost", opts, null); - extended.setSocket(mock(WebSocketClient.class)); - extended.setState(States.CONNECTED); - kuzzle = spy(extended); - when(kuzzle.getHeaders()).thenReturn(new JSONObject()); - - security = new Security(kuzzle); - listener = mock(ResponseListener.class); - options = mock(Options.class); - scroll = new Scroll(); - scrollId = "f00ba5"; - } - - @Test(expected = IllegalArgumentException.class) - public void testScrollUsersNoScrollId() throws JSONException { - security.scrollUsers(scroll, null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testScrollUsersIllegalListener() throws JSONException { - scroll.setScrollId(scrollId); - security.scrollUsers(scroll, null); - } - - @Test - public void checkSignaturesVariants() throws JSONException { - security = spy(security); - scroll.setScrollId(scrollId); - - security.scrollUsers(scroll, listener); - verify(security).scrollUsers(eq(scroll), eq(listener)); - - security.scrollUsers(scroll, options, listener); - verify(security).scrollUsers(eq(scroll), eq(options), eq(listener)); - } - - @Test(expected = RuntimeException.class) - public void testScrollUsersQueryException() throws JSONException { - scroll.setScrollId(scrollId); - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - security.scrollUsers(scroll, listener); - } - - @Test(expected = RuntimeException.class) - public void testScrollUsersException() throws JSONException { - scroll.setScrollId(scrollId); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("count", 42))); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - doThrow(JSONException.class).when(listener).onSuccess(any(Integer.class)); - security.scrollUsers(scroll, listener); - } - - @Test - public void testScrollUsers() throws JSONException { - scroll.setScrollId("f00ba5"); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject("{\"result\": {\n" + - " \"_shards\": {\n" + - " \"failed\": 0,\n" + - " \"successful\": 5,\n" + - " \"total\": 5\n" + - " },\n" + - " \"hits\": [\n" + - " {\n" + - " \"_id\": \"AVJAwyDMZAGQHg9Dhfw2\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073821,\n" + - " \"lon\": 3.9130721\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"customer\"\n" + - " },\n" + - " \"_meta\": {},\n" + - " \"_type\": \"users\"\n" + - " },\n" + - " {\n" + - " \"_id\": \"AVJAwyOvZAGQHg9Dhfw3\",\n" + - " \"_index\": \"cabble\",\n" + - " \"_score\": 1,\n" + - " \"_source\": {\n" + - " \"pos\": {\n" + - " \"lat\": 43.6073683,\n" + - " \"lon\": 3.8999983\n" + - " },\n" + - " \"sibling\": \"none\",\n" + - " \"status\": \"idle\",\n" + - " \"type\": \"cab\"\n" + - " },\n" + - " \"_meta\": {},\n" + - " \"_type\": \"users\"\n" + - " }\n" + - " ],\n" + - " \"max_score\": 1,\n" + - " \"timed_out\": false,\n" + - " \"took\": 307,\n" + - " \"total\": 2\n" + - " }" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject()); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - security.scrollUsers(scroll, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList result) { - assertEquals(result.getTotal(), 2); - assertEquals(result.getDocuments().get(1).getId(), "AVJAwyOvZAGQHg9Dhfw3"); - } - - @Override - public void onError(JSONObject error) { - } - }); - security.scrollUsers(scroll, mock(ResponseListener.class)); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "scrollUsers"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchProfilesTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchProfilesTest.java deleted file mode 100644 index 277689c6..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchProfilesTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.SecurityDocumentList; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class searchProfilesTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testSearchProfilesNoFilters() throws JSONException { - kuzzleSecurity.searchProfiles(null, null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testSearchProfilesNoListener() throws JSONException { - kuzzleSecurity.searchProfiles(new JSONObject(), null); - } - - @Test - public void testSearchProfilesValid() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"hits\": [" + - "{" + - "\"_id\": \"foobar\"," + - "\"_source\": {" + - "\"_id\": \"foobar\"," + - "\"indexes\": {}" + - "}," + - "\"_meta\": {}" + - "}" + - "]," + - "\"total\": 1" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.searchProfiles(new JSONObject(), null, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList response) { - assertEquals(response.getTotal(), 1); - assertEquals(response.getDocuments().get(0).id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "searchProfiles"); - } - - @Test(expected = RuntimeException.class) - public void testSearchProfilesBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.searchProfiles(new JSONObject(), null, listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchRolesTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchRolesTest.java deleted file mode 100644 index 3f48f745..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchRolesTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.SecurityDocumentList; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class searchRolesTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testSearchRolesNoFilters() throws JSONException { - kuzzleSecurity.searchRoles(null, null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testSearchRolesNoListener() throws JSONException { - kuzzleSecurity.searchRoles(new JSONObject(), null); - } - - @Test - public void testSearchRolesValid() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"hits\": [" + - "{" + - "\"_id\": \"foobar\"," + - "\"_source\": {" + - "\"_id\": \"foobar\"," + - "\"indexes\": {}" + - "}," + - "\"_meta\": {}" + - "}" + - "]," + - "\"total\": 1" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.searchRoles(new JSONObject(), null, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList response) { - assertEquals(response.getTotal(), 1); - assertEquals(response.getDocuments().get(0).id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "searchRoles"); - } - - @Test(expected = RuntimeException.class) - public void testSearchRolesBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.searchRoles(new JSONObject(), null, listener); - } - -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchUsersTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchUsersTest.java deleted file mode 100644 index 99609707..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/searchUsersTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.responses.SecurityDocumentList; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class searchUsersTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testSearchUsersNoFilters() throws JSONException { - kuzzleSecurity.searchUsers(null, null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testSearchUsersNoListener() throws JSONException { - kuzzleSecurity.searchUsers(new JSONObject(), null); - } - - @Test - public void testSearchUsersValid() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"hits\": [" + - "{" + - "\"_id\": \"foobar\"," + - "\"_source\": {" + - "\"_id\": \"foobar\"," + - "\"indexes\": {}" + - "}," + - "\"_meta\": {}" + - "}" + - "]," + - "\"total\": 1" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.searchUsers(new JSONObject(), null, new ResponseListener() { - @Override - public void onSuccess(SecurityDocumentList response) { - assertEquals(response.getTotal(), 1); - assertEquals(response.getDocuments().get(0).id, "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "searchUsers"); - } - - @Test(expected = RuntimeException.class) - public void testSearchUsersBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.searchUsers(new JSONObject(), null, listener); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateCredentialsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateCredentialsTest.java deleted file mode 100644 index cabb6990..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateCredentialsTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Security; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class updateCredentialsTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - private JSONObject credentials = mock(JSONObject.class); - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testUpdateCredentialsException() throws JSONException { - listener = spy(listener); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.updateCredentials("strategy", "kuid", credentials, null, listener); - } - - @Test(expected = RuntimeException.class) - public void testUpdateCredentialsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.updateCredentials("strategy", "kuid", credentials, null, listener); - } - - @Test - public void testUpdateCredentials() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject())); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzleSecurity.updateCredentials("strategy", "kuid", credentials) - .updateCredentials("strategy", "kuid", credentials, mock(Options.class)) - .updateCredentials("strategy", "kuid", credentials, mock(ResponseListener.class)) - .updateCredentials("strategy", "kuid", credentials, mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(4)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "updateCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateProfileTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateProfileTest.java deleted file mode 100644 index 15383022..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateProfileTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Profile; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class updateProfileTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - private JSONObject[] policies; - - @Before - public void setUp() throws JSONException { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - policies = new JSONObject[]{new JSONObject().put("foo", "bar")}; - } - - @Test - public void testUpdateProfileNoListener() throws JSONException { - kuzzleSecurity.updateProfile("foo", policies, new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "updateProfile"); - } - - @Test - public void testUpdateProfileValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.updateProfile("foobar", policies, new ResponseListener() { - @Override - public void onSuccess(Profile response) { - assertEquals(response.getId(), "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "updateProfile"); - } - - @Test(expected = RuntimeException.class) - public void testUpdateProfileBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.updateProfile("foobar", policies, new Options(), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testUpdateProfileNoID() throws JSONException { - kuzzleSecurity.updateProfile(null, policies); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateRoleTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateRoleTest.java deleted file mode 100644 index 964def24..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateRoleTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Role; -import io.kuzzle.sdk.security.Security; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class updateRoleTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - private JSONObject content; - - @Before - public void setUp() throws JSONException { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - content = new JSONObject() - .put("foo", "bar"); - } - - @Test - public void testUpdateRoleNoListener() throws JSONException { - kuzzleSecurity.updateRole("foo", content, new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "updateRole"); - } - - @Test - public void testUpdateRoleValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.updateRole("foobar", content, new ResponseListener() { - @Override - public void onSuccess(Role role) { - assertEquals(role.getId(), "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "updateRole"); - } - - @Test(expected = RuntimeException.class) - public void testUpdateRoleBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.updateRole("foobar", content, new Options(), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testUpdateRoleNoID() throws JSONException { - kuzzleSecurity.updateRole(null, content); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateUserTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateUserTest.java deleted file mode 100644 index 634f6337..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/updateUserTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.security.User; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class updateUserTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - private JSONObject content; - - @Before - public void setUp() throws JSONException { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - listener = mock(ResponseListener.class); - content = new JSONObject() - .put("foo", "bar"); - } - - @Test - public void testUpdateUserNoListener() throws JSONException { - kuzzleSecurity.updateUser("foo", content, new Options()); - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "updateUser"); - } - - @Test - public void testUpdateUserValidResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject( - "{" + - "\"result\": {" + - "\"_id\": \"foobar\"," + - "\"_source\": {}," + - "\"_meta\": {}" + - "}" + - "}"); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.updateUser("foobar", content, new ResponseListener() { - @Override - public void onSuccess(User response) { - assertEquals(response.getId(), "foobar"); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "updateUser"); - } - - @Test(expected = RuntimeException.class) - public void testUpdateUserBadResponse() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - JSONObject response = new JSONObject(); - - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - kuzzleSecurity.updateUser("foobar", content, new Options(), listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testUpdateUserNoID() throws JSONException { - kuzzleSecurity.updateUser(null, content); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/validateCredentialsTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/validateCredentialsTest.java deleted file mode 100644 index bf814c3d..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleSecurity/validateCredentialsTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package main.java.io.kuzzle.sdk.security.KuzzleSecurity; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.security.Security; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -public class validateCredentialsTest { - private Kuzzle kuzzle; - private Security kuzzleSecurity; - private ResponseListener listener; - private JSONObject credentials; - - @Before - public void setUp() { - kuzzle = mock(Kuzzle.class); - kuzzleSecurity = new Security(kuzzle); - credentials = mock(JSONObject.class); - listener = new ResponseListener() { - @Override - public void onSuccess(Object response) { - - } - - @Override - public void onError(JSONObject error) { - - } - }; - } - - @Test(expected = RuntimeException.class) - public void testValidateCredentialsException() throws JSONException { - listener = spy(listener); - doThrow(JSONException.class).when(listener).onSuccess(any(JSONObject.class)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(mock(JSONObject.class)); - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.validateCredentials("strategy", "kuid", credentials, null, listener); - } - - @Test(expected = RuntimeException.class) - public void testValidateCredentialsQueryException() throws JSONException { - doThrow(JSONException.class).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - kuzzleSecurity.validateCredentials("strategy", "kuid", credentials, null, listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testListenerNull() { - kuzzleSecurity.validateCredentials("strategy", "kuid", credentials, null, null); - } - - @Test - public void testValidateCredentials() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArguments()[3] != null) { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", true)); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - } - return null; - } - }).when(kuzzle).query(any(Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Kuzzle.QueryArgs.class); - - kuzzleSecurity.validateCredentials("strategy", "kuid", credentials, mock(ResponseListener.class)); - kuzzleSecurity.validateCredentials("strategy", "kuid", credentials, mock(Options.class), mock(ResponseListener.class)); - - verify(kuzzle, times(2)).query((Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((Kuzzle.QueryArgs) argument.getValue()).action, "validateCredentials"); - } -} diff --git a/test/main/java/io/kuzzle/sdk/security/KuzzleUserTest.java b/test/main/java/io/kuzzle/sdk/security/KuzzleUserTest.java deleted file mode 100644 index bfb18f23..00000000 --- a/test/main/java/io/kuzzle/sdk/security/KuzzleUserTest.java +++ /dev/null @@ -1,408 +0,0 @@ -package main.java.io.kuzzle.sdk.security; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.security.Profile; -import io.kuzzle.sdk.security.Security; -import io.kuzzle.sdk.security.User; - -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class KuzzleUserTest { - private Kuzzle kuzzle; - private User stubUser; - - @Before - public void setUp() throws JSONException { - kuzzle = mock(Kuzzle.class); - kuzzle.security = new Security(kuzzle); - stubUser = new User(kuzzle, "foo", null, null); - } - - @Test - public void testKuzzleUserConstructorNoContent() throws JSONException { - User user = new User(kuzzle, "foo", null, null); - assertEquals(user.id, "foo"); - assertEquals(user.getProfileIds().length, 0); - assertThat(user.content, instanceOf(JSONObject.class)); - } - - @Test - public void testKuzzleUserConstructorWithEmptyProfile() throws JSONException { - JSONObject stubProfile = new JSONObject( - "{" + - "\"profileIds\": [\"bar\"]," + - "\"someuseless\": \"field\"" + - "}" - ); - User user = new User(kuzzle, "foo", stubProfile, null); - assertEquals(user.id, "foo"); - assertEquals(user.getProfileIds()[0], "bar"); - assertThat(user.content, instanceOf(JSONObject.class)); - assertEquals(user.content.getString("someuseless"), "field"); - } - - @Test - public void testKuzzleUserConstructorProfileWithContent() throws JSONException { - JSONObject stubProfile = new JSONObject("{\"profileIds\": [\"bar\"]}"); - User user = new User(kuzzle, "foo", stubProfile, null); - assertEquals(user.id, "foo"); - assertThat(user.getProfileIds(), instanceOf(String[].class)); - assertEquals(user.getProfileIds()[0], "bar"); - assertThat(user.content, instanceOf(JSONObject.class)); - } - - @Test - public void testKuzzleUserConstructorMeta() throws JSONException { - JSONObject meta = new JSONObject() - .put("createdAt", "0123456789") - .put("author", "-1"); - User user = new User(kuzzle, "foo", null, meta); - assertEquals(user.id, "foo"); - assertEquals(user.getMeta().length(), 2); - assertEquals(user.getMeta().getString("createdAt"), "0123456789"); - assertEquals(user.getMeta().getString("author"), "-1"); - assertThat(user.meta, instanceOf(JSONObject.class)); - } - - @Test - public void testSetProfileWithKuzzleProfile() throws JSONException { - String[] ids = new String[1]; - ids[0] = "foo"; - stubUser.setProfiles(ids); - assertEquals(stubUser.getProfileIds()[0], "foo"); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetProfileNullID() throws JSONException { - String[] ids = null; - stubUser.setProfiles(ids); - doThrow(IllegalArgumentException.class).when(stubUser).setProfiles(any(String[].class)); - } - - @Test - public void testReplaceNoListener() throws JSONException { - stubUser.replace(); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "replaceUser"); - } - - @Test - public void testReplace() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject()); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubUser.replace(new ResponseListener() { - @Override - public void onSuccess(User response) { - assertEquals(response, stubUser); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - stubUser.replace(mock(Options.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "replaceUser"); - } - - @Test - public void testCreateNoListener() throws JSONException { - stubUser.create(); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createUser"); - } - - @Test - public void testCreate() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject()); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubUser.create(new ResponseListener() { - @Override - public void onSuccess(User response) { - assertEquals(response, stubUser); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - stubUser.create(mock(Options.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createUser"); - } - - @Test - public void testSaveRestrictedNoListener() throws JSONException { - stubUser.saveRestricted(); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createRestrictedUser"); - } - - @Test - public void testSaveRestrictedNoListenerAndOptions() throws JSONException { - Options options = new Options(); - stubUser.saveRestricted(options); - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createRestrictedUser"); - } - - @Test - public void testSaveRestricted() throws JSONException { - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject()); - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); - return null; - } - }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - - stubUser.saveRestricted(new ResponseListener() { - @Override - public void onSuccess(User response) { - assertEquals(response, stubUser); - } - - @Override - public void onError(JSONObject error) { - try { - assertEquals(error.getString("error"), "stub"); - } catch (JSONException e) { - throw new RuntimeException(e); - } - } - }); - stubUser.saveRestricted(mock(Options.class)); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class)); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); - assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "createRestrictedUser"); - } - - @Test - public void testSerializeNoProfile() throws JSONException { - stubUser.content.put("foo", "bar"); - JSONObject serialized = stubUser.serialize(); - assertEquals(serialized.getString("_id"), stubUser.id); - assertEquals(serialized.getJSONObject("body").toString(), stubUser.content.toString()); - assertEquals(serialized.has("profile"), false); - } - - @Test - public void testSerializeWithProfile() throws JSONException { - stubUser.content.put("foo", "bar"); - stubUser.setProfiles(new String[]{"profile"}); - JSONObject serialized = stubUser.serialize(); - assertEquals(serialized.getString("_id"), stubUser.id); - assertEquals(serialized.getJSONObject("body").getString("foo"), "bar"); - assertEquals(serialized.getJSONObject("body").getJSONArray("profileIds").getString(0), stubUser.getProfileIds()[0]); - } - - @Test - public void testGetProfileIds() throws JSONException { - JSONObject stubProfile = new JSONObject( - "{\"profileIds\": [\"bar\"]}" - ); - User user = new User(kuzzle, "foo", stubProfile, null); - assertEquals(user.getProfileIds()[0], "bar"); - } - - @Test - public void testAddProfile() throws JSONException { - JSONObject stubProfile = new JSONObject( - "{\"profileIds\": [\"bar\"]}" - ); - User user = new User(kuzzle, "foo", stubProfile, null); - user.addProfile("new profile"); - assertEquals(user.getProfileIds()[1], "new profile"); - } - - @Test(expected = IllegalArgumentException.class) - public void testAddNullProfile() throws JSONException { - JSONObject stubProfile = new JSONObject( - "{\"profileIds\": [\"bar\"]}" - ); - User user = new User(kuzzle, "foo", stubProfile, null); - user.addProfile(null); - doThrow(IllegalArgumentException.class).when(user).addProfile(eq((String)null)); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetProfilesException() throws JSONException { - User user = new User(kuzzle, "foo", new JSONObject(), null); - user.getProfiles(null); - } - - @Test - public void testGetProfilesEmpty() throws JSONException { - User user = new User(kuzzle, "foo", new JSONObject(), null); - - user.getProfiles(new ResponseListener() { - @Override - public void onSuccess(Profile[] response) { - assertEquals(response.length, 0); - } - - @Override - public void onError(JSONObject error) { - fail("onError callback should not have been invoked"); - } - }); - } - - @Test - public void testGetProfiles() throws JSONException { - JSONArray profiles = new JSONArray().put("foo").put("bar").put("baz"); - User user = new User(kuzzle, "foo", new JSONObject().put("profileIds", profiles), null); - - Answer mockAnswer = new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation - .getArguments()[3]) - .onSuccess(new JSONObject() - .put("result", new JSONObject() - .put("_id", "foobar") - .put("_source", new JSONObject() - .put("policies", new JSONArray()) - ) - .put("_meta", new JSONObject()) - ) - ); - return null; - } - }; - - doAnswer(mockAnswer) - .when(kuzzle) - .query( - any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), - any(JSONObject.class), - any(Options.class), - any(OnQueryDoneListener.class) - ); - - user.getProfiles(new ResponseListener() { - @Override - public void onSuccess(Profile[] response) { - assertEquals(response.length, 3); - } - - @Override - public void onError(JSONObject error) { - fail("onError should not have been invoked"); - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } - - @Test - public void testGetProfilesError() throws JSONException { - JSONArray profiles = new JSONArray().put("foo").put("bar").put("baz"); - User user = new User(kuzzle, "foo", new JSONObject().put("profileIds", profiles), null); - final boolean[] invoked = {false}; - - Answer mockAnswer = new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); - return null; - } - }; - - doAnswer(mockAnswer) - .when(kuzzle) - .query( - any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), - any(JSONObject.class), - any(Options.class), - any(OnQueryDoneListener.class) - ); - - user.getProfiles(new ResponseListener() { - @Override - public void onSuccess(Profile[] response) { - fail("onSuccess should not have been invoked"); - } - - @Override - public void onError(JSONObject error) { - if (invoked[0] == true) { - fail("onError invoked more than once"); - return; - } - - invoked[0] = true; - } - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); - verify(kuzzle, times(3)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); - } -} diff --git a/test/main/java/io/kuzzle/sdk/testUtils/KuzzleDataCollectionExtend.java b/test/main/java/io/kuzzle/sdk/testUtils/KuzzleDataCollectionExtend.java deleted file mode 100644 index f4ed77c5..00000000 --- a/test/main/java/io/kuzzle/sdk/testUtils/KuzzleDataCollectionExtend.java +++ /dev/null @@ -1,18 +0,0 @@ -package main.java.io.kuzzle.sdk.testUtils; - -import org.json.JSONObject; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.listeners.ResponseListener; - -public class KuzzleDataCollectionExtend extends Collection { - public KuzzleDataCollectionExtend(final Kuzzle kuzzle, final String index, final String collection) { - super(kuzzle, collection, index); - } - - public Collection deleteDocument(final String documentId, final JSONObject filter, final Options options, final ResponseListener listener, final ResponseListener listener2) { - return super.deleteDocument(documentId, filter, options, listener, listener2); - } -} diff --git a/test/main/java/io/kuzzle/sdk/testUtils/KuzzleExtend.java b/test/main/java/io/kuzzle/sdk/testUtils/KuzzleExtend.java deleted file mode 100644 index f1ce41f6..00000000 --- a/test/main/java/io/kuzzle/sdk/testUtils/KuzzleExtend.java +++ /dev/null @@ -1,131 +0,0 @@ -package main.java.io.kuzzle.sdk.testUtils; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.net.URISyntaxException; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import io.kuzzle.sdk.core.Kuzzle; -import io.kuzzle.sdk.core.Options; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.enums.Event; -import io.kuzzle.sdk.listeners.ResponseListener; -import io.kuzzle.sdk.listeners.OnQueryDoneListener; -import io.kuzzle.sdk.state.States; -import io.kuzzle.sdk.util.EventList; -import tech.gusavila92.websocketclient.WebSocketClient; - -import static org.mockito.Mockito.spy; - -public class KuzzleExtend extends Kuzzle { - protected WebSocketClient savedSocket = null; - - public ResponseListener loginCallback; - - public KuzzleExtend(final String host, final Options options, final ResponseListener connectionCallback) throws URISyntaxException { - super(host, options, connectionCallback); - } - - public void setState(States newState) { - this.state = newState; - } - - public void setSocket(WebSocketClient s) { - this.socket = this.savedSocket = s; - } - - public void setListener(ResponseListener listener) { - this.connectionCallback = listener; - } - - - public Kuzzle deleteSubscription(final String roomId, final String id) { - return super.deleteSubscription(roomId, id); - } - - - protected WebSocketClient createSocket() throws URISyntaxException { - return this.savedSocket != null ? this.savedSocket : super.createSocket(); - } - - /** - * * Returns all registered listeners on a given event - * - * @param event - */ - public EventList getEventListeners(Event event) { - return this.eventListeners.get(event); - } - - /** - * Get the subscription object from a Kuzzle instance - * - * @return - */ - public Map> getSubscriptions() { - return this.subscriptions; - } - - /** - * Gets the internal socket instance from the kuzzle object - * @return - */ - public WebSocketClient getSocket() { - return this.socket; - } - - public void isValid() { - super.isValid(); - } - - public void emitRequest(final JSONObject request, final OnQueryDoneListener listener) throws JSONException { - super.emitRequest(request, listener); - } - - public Kuzzle deletePendingSubscription(final String id) { - return super.deletePendingSubscription(id); - } - - public Map getRequestHistory() { - return super.getRequestHistory(); - } - - public Map getPendingSubscriptions() { - return super.getPendingSubscriptions(); - } - - public boolean isValidState() { - return super.isValidState(); - } - - public ResponseListener spyAndGetConnectionCallback() { - super.connectionCallback = spy(super.connectionCallback); - return super.connectionCallback; - } - - public void setSuperDefaultIndex(final String index) { - super.defaultIndex = index; - } - - public void emitEvent(final Event event, final Object... args) { - super.emitEvent(event, args); - } - - public void renewSubscriptions() { - super.renewSubscriptions(); - } - - public void setJwtTokenWithoutSubscribe(final String token) { - super.jwtToken = token; - } - - public Kuzzle removeRoom(String channel) { - super.removeRoom(channel); - - return this; - } - -} diff --git a/test/main/java/io/kuzzle/sdk/testUtils/QueryArgsHelper.java b/test/main/java/io/kuzzle/sdk/testUtils/QueryArgsHelper.java deleted file mode 100644 index 45aea3dd..00000000 --- a/test/main/java/io/kuzzle/sdk/testUtils/QueryArgsHelper.java +++ /dev/null @@ -1,10 +0,0 @@ -package main.java.io.kuzzle.sdk.testUtils; - -public class QueryArgsHelper { - public static io.kuzzle.sdk.core.Kuzzle.QueryArgs makeQueryArgs(final String controller, final String action) { - io.kuzzle.sdk.core.Kuzzle.QueryArgs args = new io.kuzzle.sdk.core.Kuzzle.QueryArgs(); - args.controller = controller; - args.action = action; - return args; - } -} diff --git a/test/main/java/io/kuzzle/sdk/testUtils/RoomExtend.java b/test/main/java/io/kuzzle/sdk/testUtils/RoomExtend.java deleted file mode 100644 index 593c62ef..00000000 --- a/test/main/java/io/kuzzle/sdk/testUtils/RoomExtend.java +++ /dev/null @@ -1,62 +0,0 @@ -package main.java.io.kuzzle.sdk.testUtils; - -import org.json.JSONObject; - -import java.util.Timer; -import java.util.TimerTask; - -import io.kuzzle.sdk.core.Collection; -import io.kuzzle.sdk.core.Room; -import io.kuzzle.sdk.core.RoomOptions; -import io.kuzzle.sdk.listeners.ResponseListener; - -public class RoomExtend extends Room { - - public RoomExtend(Collection kuzzleDataCollection) { - super(kuzzleDataCollection); - } - - public RoomExtend(Collection kuzzleDataCollection, RoomOptions options) { - super(kuzzleDataCollection, options); - } - - public void callAfterRenew(Object args) { - super.callAfterRenew(args); - } - - public void setListener(final ResponseListener listener) { - this.listener = listener; - } - - public void setRoomId(final String id) { - this.roomId = id; - } - - public void setSubscribing(final boolean isSubscribing) { - super.subscribing = isSubscribing; - } - - public void dequeue() { - super.dequeue(); - } - - @Override - public Room unsubscribe() { - // do nothing - return this; - } - - public Room superUnsubscribe() { - return super.unsubscribe(); - } - - public TimerTask unsubscribeTask(final Timer timer, final String roomId, final JSONObject data) { - return super.unsubscribeTask(timer, roomId, data); - } - - public Room makeHeadersNull() { - super.headers = null; - return this; - } - -}