From 5ee86b12775886cfe89dc3fab7ad7437b645909e Mon Sep 17 00:00:00 2001 From: Rolljee Date: Tue, 22 Dec 2020 17:48:37 +0100 Subject: [PATCH 01/11] Add Github actions --- .github/actions/dead-links/action.yml | 23 ++++ .github/actions/deploy/action.yml | 20 +++ .github/actions/doc-deploy/action.yml | 53 ++++++++ .github/actions/snippets-tests/action.yml | 8 ++ .github/actions/unit-tests/action.yml | 8 ++ .github/workflows/pull_request.workflow.yml | 57 +++++++++ .github/workflows/push_dev.workflow.yml | 68 ++++++++++ .github/workflows/push_master.workflow.yml | 80 ++++++++++++ .travis.yml | 131 -------------------- 9 files changed, 317 insertions(+), 131 deletions(-) create mode 100644 .github/actions/dead-links/action.yml create mode 100644 .github/actions/deploy/action.yml create mode 100644 .github/actions/doc-deploy/action.yml create mode 100644 .github/actions/snippets-tests/action.yml create mode 100644 .github/actions/unit-tests/action.yml create mode 100644 .github/workflows/pull_request.workflow.yml create mode 100644 .github/workflows/push_dev.workflow.yml create mode 100644 .github/workflows/push_master.workflow.yml delete mode 100644 .travis.yml diff --git a/.github/actions/dead-links/action.yml b/.github/actions/dead-links/action.yml new file mode 100644 index 00000000..e8fec33b --- /dev/null +++ b/.github/actions/dead-links/action.yml @@ -0,0 +1,23 @@ +name: Dead Links +description: Run Dead Links Tests +runs: + using: "composite" + steps: + - name: Install deps + run: npm ci + shell: bash + - name: Prepare documentation + run: npm run doc-prepare + shell: bash + - name: Install docs repositories + run: npx kuzdoc iterate-repos:install --repos_path doc/framework/.repos/ + shell: bash + - name: Link kuzdoc + run: npx kuzdoc framework:link -d /sdk/jvm/1/ -v 1 + shell: bash + - name: Install typhoeus + run: sudo gem install typhoeus + shell: bash + - name: Run dead links tests + run: cd doc/framework/ && HYDRA_MAX_CONCURRENCY=20 ruby .ci/dead-links.rb -p src/sdk/jvm/1/ + shell: bash diff --git a/.github/actions/deploy/action.yml b/.github/actions/deploy/action.yml new file mode 100644 index 00000000..29969444 --- /dev/null +++ b/.github/actions/deploy/action.yml @@ -0,0 +1,20 @@ +name: Deploy package +description: Run Deploy package + +inputs: + BINTRAY_KEY: + description: BINTRAY_KEY + required: true + BINTRAY_USER: + description: BINTRAY_USER + required: true + +runs: + using: "composite" + steps: + - name: Deploy to bintray + run: ./gradlew bintrayUpload + env: + BINTRAY_KEY: ${{ inputs.BINTRAY_KEY }} + BINTRAY_USER: ${{ inputs.BINTRAY_USER }} + shell: bash diff --git a/.github/actions/doc-deploy/action.yml b/.github/actions/doc-deploy/action.yml new file mode 100644 index 00000000..0570d8f1 --- /dev/null +++ b/.github/actions/doc-deploy/action.yml @@ -0,0 +1,53 @@ +name: Deploy Documentation +description: Build doc, upload it to S3 and invalidate Cloudfront cache + +inputs: + AWS_ACCESS_KEY_ID: + description: AWS Access key ID + required: true + AWS_SECRET_ACCESS_KEY: + description: AWS secret key + required: true + S3_BUCKET: + description: S3 bucket name + required: true + CLOUDFRONT_ID: + description: Cloudfront distribution ID + required: true + REGION: + description: AWS default region + required: true + FRAMEWORK_BRANCH: + description: Documentation framework branch to use + required: true + +runs: + using: "composite" + steps: + - name: Install AWS CLI + run: | + sudo apt-get update + sudo apt-get install python python-pip + pip install awscli --upgrade --user + shell: bash + - name: Build documentation + run: | + rm -fr doc/framework + npm install --production=false + npm run doc-prepare + npm run doc-build + env: + NODE_ENV: production + FRAMEWORK_BRANCH: ${{ inputs.FRAMEWORK_BRANCH }} + shell: bash + - name: Deploy documentation + run: | + npm run doc-upload + npm run doc-cloudfront + env: + AWS_DEFAULT_REGION: ${{ inputs.REGION }} + AWS_ACCESS_KEY_ID: ${{ inputs.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ inputs.AWS_SECRET_ACCESS_KEY }} + S3_BUCKET: ${{ inputs.S3_BUCKET }} + CLOUDFRONT_DISTRIBUTION_ID: ${{ inputs.CLOUDFRONT_ID }} + shell: bash diff --git a/.github/actions/snippets-tests/action.yml b/.github/actions/snippets-tests/action.yml new file mode 100644 index 00000000..e935d83f --- /dev/null +++ b/.github/actions/snippets-tests/action.yml @@ -0,0 +1,8 @@ +name: Snippets Tests +description: Run Snippets Testss +runs: + using: "composite" + steps: + - name: Launch Tests + run: docker-compose -f .ci/doc/docker-compose.yml run doc-tests index + shell: bash diff --git a/.github/actions/unit-tests/action.yml b/.github/actions/unit-tests/action.yml new file mode 100644 index 00000000..e056a20b --- /dev/null +++ b/.github/actions/unit-tests/action.yml @@ -0,0 +1,8 @@ +name: Unit Test +description: Run Unit Tests +runs: + using: "composite" + steps: + - name: Launch Tests + run: ./gradlew test + shell: bash diff --git a/.github/workflows/pull_request.workflow.yml b/.github/workflows/pull_request.workflow.yml new file mode 100644 index 00000000..5dc18823 --- /dev/null +++ b/.github/workflows/pull_request.workflow.yml @@ -0,0 +1,57 @@ +name: Pull request checks + +on: [pull_request] + +jobs: + unit-tests: + name: unit-tests + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: "8.0.0" + architecture: x64 + - uses: ./.github/actions/unit-tests + + snippets-tests: + name: Snippets Tests + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - uses: actions/setup-node@v1.4.4 + with: + node-version: "12" + - uses: ./.github/actions/snippets-tests + + dead-links: + name: Dead links + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - uses: actions/setup-node@v1.4.4 + with: + node-version: "12" + - uses: ./.github/actions/dead-links diff --git a/.github/workflows/push_dev.workflow.yml b/.github/workflows/push_dev.workflow.yml new file mode 100644 index 00000000..00334f13 --- /dev/null +++ b/.github/workflows/push_dev.workflow.yml @@ -0,0 +1,68 @@ +name: Deployment Doc Dev + +on: + push: + branches: + - 1-dev + +jobs: + unit-tests: + name: unit-tests + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: '8.0.0' + architecture: x64 + - uses: ./.github/actions/unit-tests + + snippets-tests: + name: Snippets Tests + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - uses: actions/setup-node@v1.4.4 + with: + node-version: "12" + - uses: ./.github/actions/snippets-tests + + doc-dev: + name: Deployment Doc Dev + runs-on: ubuntu-18.04 + needs: [unit-tests, snippets-tests] + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - uses: actions/setup-node@v1 + with: + node-version: "12" + - uses: ./.github/actions/doc-deploy + with: + REGION: us-west-2 + S3_BUCKET: docs-next.kuzzle.io + CLOUDFRONT_ID: E2ZCCEK9GRB49U + FRAMEWORK_BRANCH: develop + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} diff --git a/.github/workflows/push_master.workflow.yml b/.github/workflows/push_master.workflow.yml new file mode 100644 index 00000000..b7d21fc8 --- /dev/null +++ b/.github/workflows/push_master.workflow.yml @@ -0,0 +1,80 @@ +name: Deployment Doc Dev + +on: + push: + branches: + - master + +jobs: + unit-tests: + name: unit-tests + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: "8.0.0" + architecture: x64 + - uses: ./.github/actions/unit-tests + + snippets-tests: + name: Snippets Tests + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - uses: actions/setup-node@v1.4.4 + with: + node-version: "12" + - uses: ./.github/actions/snippets-tests + + doc-master: + name: Deployment Doc master + runs-on: ubuntu-18.04 + needs: [unit-tests, snippets-tests] + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - uses: actions/setup-node@v1 + with: + node-version: "12" + - uses: ./.github/actions/doc-deploy + with: + REGION: us-west-2 + S3_BUCKET: docs.kuzzle.io + CLOUDFRONT_ID: E3D6RP0POLCJMM + FRAMEWORK_BRANCH: master + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + + deploy-bintray: + name: Deploy to Bintray + needs: [unit-tests, snippets-tests, doc-master] + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: "8.0.0" + architecture: x64 + - uses: ./.github/actions/deploy diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index e1d8a3e2..00000000 --- a/.travis.yml +++ /dev/null @@ -1,131 +0,0 @@ -env: - global: - # BINTRAY_USER - - secure: YJWM5LX2dCCZjWKen4mLxrXuGk1E/kcyOunO1J+KJdFtEYUeV8e4y5u3mzYDfcU/ovPYBjvNc8nDAnOKq5NuqwqqYegKRa+h90Xzi5ZsVsL7M7NHmnBL1gtxhG2NNYgk6GbPxYfT1FBG6vWyd7DICf87Qt5U9SitPr+XYi/5rxf0hkF6fPIVemOVaRuA3po38eu3oRt5zxtXQ5sRM+NcgxE+ALxeHxX6c8qAARxQcgS+QP8ET7vUI0GYS1j0EAErqvCzz91EwlDMHAv6MUXuz7kzZyeLdWAjEW/xPTsXAehGb/oNmXZUvERh2KXay9NdT8EsipH4f0Rl/KKX2/auweoVPKGcHL1g+mOatyFNNxQZ7wtCv/JqXTj6Y9vwlLHSESy5rmMG7GleZevXLjO/wWd5yWIKmwxhvvUrZeUHLo5w/EgPlx8h3myjl2003Qhg2BCjGw/CVqbDolmVBIf6yNEWd5Fp+UL/govR3x7+EUIe5YCqcVy71XjGxwd7i6R9YKmseZqQmdAzanKnr8Pbe5ppH2bPUJxuWH8MdQUwifGttlh/IyKgqbkoxfvS+5SqipNhJky2bjX+x35EoTlAQkaw0YRiGtfmb6nEUXZgKa+uvR4vi0NHGUe3uzvsZjxtHFkM1T4Ysr3RUmYDfpj2ymCQbzQqC8nnQoeyXEe6Ue4= - # BINTRAY_KEY - - secure: PsUWWzEPYXymGVtnDJmHNxRmPYnw7v0Ucsvx672w6O9tpfyL2dADwGuhxnGjLXuifN8b8LAFPHpt2Ymc++Q9bjK1Gns370klJC1yUGR+EkCMKnS7tVlaStHRt1o9WBl0hlkHada31vMmnm2NYAzR4uHU9O8mMXwiFyYo4CQVLzQajJGSZVI46JNt+hITVemdGZluw7lzmqJ0+e5N2nZNDszPkxy3jar5luLsDyNEzF/iEPhp0pMi6kPSARKZVsRDaND2cnkRQm6KwPE6RbUIr2JE/1rB9Rfz3J7ThipHgl9Czm1TK0FW8auNMwCR99UFuPC8wHGD/20mlxegi1DKniNh1ZZ+CBjVu8IhOItfVjABipzRJUb7GQqdHQWJSF5cXypS1ZVbYbATEciYMLZVCC2qDuH6zLM0JiGQCTteNBj39FjkLG+lDb7qNU2XwIuYTFgBGy3qW1+oS+Hq9q4IVAfpbnTtk0JJTrwoDm4YUotlMGgrMHuzWGvLXXUwo0JhfvAaMfE6PfpoJ0LtdrLcDlXQjeGrkjCldLiIoFEAC5CBapu6nt0b6RpsKnIJrMZZgwgsX8PTzCpL27XLb7BHQb3nRBsQAcejdFbhzOWivlDUxLnL5rHXibT1gYnBLvBEBwJv3QSs3fGGiL96nI62PMQJzJcBnDSRJ/0iMkKW5hY= - # AWS_SECRET_ACCESS_KEY - - secure: pcNtmEXTGmENiFWWbxLxPlix6ZBdYQjyr91g1zq/J7zq6jOTFV082sch1TgE1JfdXQHKpc0euc2E5Nj1i2z+ws5ZFufjg64dBe9O88Zr0HHNjbwP2qPnrJ+dJddfE91/DME9kDpjXYIftRFVoF9LeRx2JgR7XlYIZmmFyw8W+g5qsq5MgQCY2BoRKJ2aZ/raJkwBuqulgzlE66y/Yi4ZPDtxfW03XL6VrqgtFd7HAgXm6Ht0H2L50iHgky9u3TV4RdJQRYivV/mKJwd4NDcejXjdBcVmGnAol2iLnyowVcXZQ2r13/cdVJeGHGw4cUszyiOSC//Zb7Qj0UyLlkpKlje0/uEr68kK+wJ5WMZDlYZ3JiIhE+DkWXEOXtD0YvLwp/rU9hJ4sdGJKWF1VNdxp5Mv7RzkOFEinq9hBYI9SoYS3Z0tcM9waE6V4N11PRgP0sSxOr/YWHFzOZu2hdKzowXN9l5Z+tCHcOtLbLqheFNAm5kKZOY+n6iV9YLE7c8D1f14QVnjpjl2z7uX057Q+rd49NaHQnx3mrsLNrQfHoEI39sP5pWNLePjIu1YyWsiiUnlkPmroQECwWlmPBiqfF+ND+ngVgaFgZxP2QResSt0G3FfwxEA04Da4q6wfH+gNrgUjKCh/gK1Ef/VuONZB7hoEActWnV9iEa7+WlSVI8= - - AWS_ACCESS_KEY_ID=AKIAIYAXFUAHXOWP2MJA - -job: - include: - - stage: Tests - name: Unit tests SDK Kotlin - 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: - - "./gradlew test" - - stage: Tests - name: Dead link check - if: type = pull_request OR type = push AND branch =~ /^master|[0-9]+-(dev|stable)$/ - OR type = cron - language: node_js - node_js: 12 - before_script: - - npm ci - - npm run doc-prepare - - "$(npm bin)/kuzdoc iterate-repos:install --repos_path doc/framework/.repos/" - - "$(npm bin)/kuzdoc framework:link -d /sdk/jvm/1/ -v 1" - script: - - gem install typhoeus - - cd doc/framework/ && HYDRA_MAX_CONCURRENCY=20 ruby .ci/dead-links.rb -p src/sdk/jvm/1/ - - 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: Deployments - name: Deploy documentation to next-docs.kuzzle.io - if: type = push AND branch =~ /^[0-9]+-dev$/ - language: node_js - node_js: 12 - env: - - BRANCH=dev - - NODE_ENV=production - - FRAMEWORK_BRANCH=develop - - S3_BUCKET=docs-next.kuzzle.io - - CLOUDFRONT_DISTRIBUTION_ID=E2ZCCEK9GRB49U - - AWS_DEFAULT_REGION=us-west-2 - addons: - apt: - update: true - 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: Deployments - name: Deploy documentation to docs.kuzzle.io - if: type = push AND branch =~ /^master|[0-9]+-stable$/ - language: node_js - node_js: 12 - env: - - NODE_ENV=production - - FRAMEWORK_BRANCH=master - - 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: Deployments - name: Deploy to Bintray - if: branch = master AND type = push - language: java - jdk: - - openjdk8 - deploy: - provider: script - script: "./gradlew bintrayUpload" - skip_cleanup: true - on: - condition: "$TRAVIS_BRANCH = master" -stages: -- name: 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)$/ -- name: Deployments - if: type =~ /(cron|push|pull_request)/ AND branch =~ /^master|[0-9]+-(dev|stable)$/ From 1b40946b01789196eff45f4aba07af7c53a54424 Mon Sep 17 00:00:00 2001 From: Rolljee Date: Mon, 18 Jan 2021 10:06:38 +0100 Subject: [PATCH 02/11] change java jsk version --- .github/workflows/pull_request.workflow.yml | 2 +- .github/workflows/push_master.workflow.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull_request.workflow.yml b/.github/workflows/pull_request.workflow.yml index 5dc18823..76e71475 100644 --- a/.github/workflows/pull_request.workflow.yml +++ b/.github/workflows/pull_request.workflow.yml @@ -10,7 +10,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 with: - java-version: "8.0.0" + java-version: "8" architecture: x64 - uses: ./.github/actions/unit-tests diff --git a/.github/workflows/push_master.workflow.yml b/.github/workflows/push_master.workflow.yml index b7d21fc8..ab875fd0 100644 --- a/.github/workflows/push_master.workflow.yml +++ b/.github/workflows/push_master.workflow.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 with: - java-version: "8.0.0" + java-version: "8" architecture: x64 - uses: ./.github/actions/unit-tests @@ -75,6 +75,6 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 with: - java-version: "8.0.0" + java-version: "8" architecture: x64 - uses: ./.github/actions/deploy From d5401caaa7b4e31448be5700928f0275cc3319a6 Mon Sep 17 00:00:00 2001 From: Rolljee Date: Wed, 20 Jan 2021 15:23:34 +0100 Subject: [PATCH 03/11] Add timeout for unit-tests & snippets --- .github/workflows/pull_request.workflow.yml | 3 +++ .github/workflows/push_dev.workflow.yml | 3 +++ .github/workflows/push_master.workflow.yml | 3 +++ 3 files changed, 9 insertions(+) diff --git a/.github/workflows/pull_request.workflow.yml b/.github/workflows/pull_request.workflow.yml index 76e71475..53c6ef85 100644 --- a/.github/workflows/pull_request.workflow.yml +++ b/.github/workflows/pull_request.workflow.yml @@ -6,6 +6,7 @@ jobs: unit-tests: name: unit-tests runs-on: ubuntu-18.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 @@ -17,6 +18,7 @@ jobs: snippets-tests: name: Snippets Tests runs-on: ubuntu-18.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v2 - name: Cache node modules @@ -38,6 +40,7 @@ jobs: dead-links: name: Dead links runs-on: ubuntu-18.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v2 - name: Cache node modules diff --git a/.github/workflows/push_dev.workflow.yml b/.github/workflows/push_dev.workflow.yml index 00334f13..faf18f3d 100644 --- a/.github/workflows/push_dev.workflow.yml +++ b/.github/workflows/push_dev.workflow.yml @@ -9,6 +9,7 @@ jobs: unit-tests: name: unit-tests runs-on: ubuntu-18.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 @@ -20,6 +21,7 @@ jobs: snippets-tests: name: Snippets Tests runs-on: ubuntu-18.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v2 - name: Cache node modules @@ -41,6 +43,7 @@ jobs: doc-dev: name: Deployment Doc Dev runs-on: ubuntu-18.04 + timeout-minutes: 30 needs: [unit-tests, snippets-tests] steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/push_master.workflow.yml b/.github/workflows/push_master.workflow.yml index ab875fd0..7a7b1536 100644 --- a/.github/workflows/push_master.workflow.yml +++ b/.github/workflows/push_master.workflow.yml @@ -9,6 +9,7 @@ jobs: unit-tests: name: unit-tests runs-on: ubuntu-18.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 @@ -20,6 +21,7 @@ jobs: snippets-tests: name: Snippets Tests runs-on: ubuntu-18.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v2 - name: Cache node modules @@ -71,6 +73,7 @@ jobs: name: Deploy to Bintray needs: [unit-tests, snippets-tests, doc-master] runs-on: ubuntu-18.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 From d4329742df554ab4d19087f9c19c73936d45de32 Mon Sep 17 00:00:00 2001 From: Alexandre Bouthinon Date: Thu, 21 Jan 2021 11:43:00 +0100 Subject: [PATCH 04/11] Apply ktlint auto fix --- src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt | 194 ++--- .../kuzzle/sdk/controllers/AuthController.kt | 466 ++++++------ .../kuzzle/sdk/controllers/BulkController.kt | 172 ++--- .../sdk/controllers/CollectionController.kt | 381 +++++----- .../sdk/controllers/DocumentController.kt | 687 +++++++++--------- .../kuzzle/sdk/controllers/IndexController.kt | 101 +-- .../sdk/controllers/RealtimeController.kt | 326 +++++---- .../sdk/controllers/ServerController.kt | 154 ++-- .../io/kuzzle/sdk/coreClasses/SearchResult.kt | 170 ++--- .../exceptions/ApiErrorException.kt | 52 +- .../coreClasses/exceptions/KuzzleException.kt | 52 +- .../exceptions/KuzzleExceptionCode.kt | 30 +- .../exceptions/NotConnectedException.kt | 6 +- .../json/ConcurrentHashMapTypeAdapter.kt | 209 +++--- .../sdk/coreClasses/json/JsonSerializer.kt | 36 +- .../kuzzle/sdk/coreClasses/maps/KuzzleMap.kt | 463 ++++++------ .../io/kuzzle/sdk/coreClasses/maps/Null.kt | 16 +- .../sdk/coreClasses/maps/Serializable.kt | 10 +- .../coreClasses/responses/ErrorResponse.kt | 66 +- .../sdk/coreClasses/responses/Response.kt | 262 +++---- .../io/kuzzle/sdk/events/EventManager.kt | 16 +- .../sdk/handlers/NotificationHandler.kt | 2 +- .../kuzzle/sdk/protocol/AbstractProtocol.kt | 10 +- .../io/kuzzle/sdk/protocol/ProtocolState.kt | 8 +- .../io/kuzzle/sdk/protocol/WebSocket.kt | 237 +++--- .../kuzzle/sdk/protocolTest/WebSocketTests.kt | 106 ++- 26 files changed, 2162 insertions(+), 2070 deletions(-) diff --git a/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt b/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt index 82a61cdd..ebe344ac 100644 --- a/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt +++ b/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt @@ -1,12 +1,12 @@ package io.kuzzle.sdk +import io.kuzzle.sdk.controllers.AuthController +import io.kuzzle.sdk.controllers.BulkController +import io.kuzzle.sdk.controllers.CollectionController import io.kuzzle.sdk.controllers.DocumentController import io.kuzzle.sdk.controllers.IndexController -import io.kuzzle.sdk.controllers.AuthController import io.kuzzle.sdk.controllers.RealtimeController import io.kuzzle.sdk.controllers.ServerController -import io.kuzzle.sdk.controllers.CollectionController -import io.kuzzle.sdk.controllers.BulkController import io.kuzzle.sdk.coreClasses.exceptions.ApiErrorException import io.kuzzle.sdk.coreClasses.exceptions.KuzzleExceptionCode import io.kuzzle.sdk.coreClasses.exceptions.NotConnectedException @@ -15,120 +15,120 @@ import io.kuzzle.sdk.coreClasses.maps.KuzzleMap import io.kuzzle.sdk.coreClasses.responses.Response import io.kuzzle.sdk.protocol.AbstractProtocol import io.kuzzle.sdk.protocol.ProtocolState -import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import kotlin.collections.HashMap class Kuzzle { - val protocol: AbstractProtocol - val autoResubscribe: Boolean - private val queries: HashMap> = HashMap() - val instanceId: String - private val version: String = "1" - private val sdkName: String = "jvm@$version" - var authenticationToken: String? = null - val realtimeController: RealtimeController - val documentController: DocumentController - val indexController: IndexController - val authController: AuthController - val serverController: ServerController - val collectionController: CollectionController - val bulkController: BulkController - - @JvmOverloads - constructor(protocol: AbstractProtocol, autoResubscribe: Boolean = true) { - this.protocol = protocol - this.autoResubscribe = autoResubscribe - instanceId = UUID.randomUUID().toString() - realtimeController = RealtimeController(this) - documentController = DocumentController(this) - indexController = IndexController(this) - authController = AuthController(this) - serverController = ServerController(this) - collectionController = CollectionController(this) - bulkController = BulkController(this) - // @TODO Create enums for events - protocol.addListener("messageReceived", ::onMessageReceived) - protocol.addListener("networkStateChange", ::onNetworkStateChange) - } - - private fun onMessageReceived(message: String?) { - val response = Response().apply { - fromMap(JsonSerializer.deserialize(message) as ConcurrentHashMap) + val protocol: AbstractProtocol + val autoResubscribe: Boolean + private val queries: HashMap> = HashMap() + val instanceId: String + private val version: String = "1" + private val sdkName: String = "jvm@$version" + var authenticationToken: String? = null + val realtimeController: RealtimeController + val documentController: DocumentController + val indexController: IndexController + val authController: AuthController + val serverController: ServerController + val collectionController: CollectionController + val bulkController: BulkController + + @JvmOverloads + constructor(protocol: AbstractProtocol, autoResubscribe: Boolean = true) { + this.protocol = protocol + this.autoResubscribe = autoResubscribe + instanceId = UUID.randomUUID().toString() + realtimeController = RealtimeController(this) + documentController = DocumentController(this) + indexController = IndexController(this) + authController = AuthController(this) + serverController = ServerController(this) + collectionController = CollectionController(this) + bulkController = BulkController(this) + // @TODO Create enums for events + protocol.addListener("messageReceived", ::onMessageReceived) + protocol.addListener("networkStateChange", ::onNetworkStateChange) } - if (queries.size == 0 || (queries.size != 0 && (response.room == null || queries[response.room!!] == null))) { - protocol.trigger("unhandledResponse", message) - return + private fun onMessageReceived(message: String?) { + val response = Response().apply { + fromMap(JsonSerializer.deserialize(message) as ConcurrentHashMap) + } + + if (queries.size == 0 || (queries.size != 0 && (response.room == null || queries[response.room!!] == null))) { + protocol.trigger("unhandledResponse", message) + return + } + + if (response.error == null) { + queries[response.requestId]?.complete(response) + queries.remove(response.requestId) + return + } + + if (response.error?.id == null || + response.error?.id != "security.token.expired" + ) { + queries[response.requestId]?.completeExceptionally(ApiErrorException(response)) + queries.remove(response.requestId) + return + } + + queries[response.requestId]?.completeExceptionally(ApiErrorException(response)) + protocol.trigger("tokenExpired") } - if (response.error == null) { - queries[response.requestId]?.complete(response) - queries.remove(response.requestId) - return + private fun onNetworkStateChange(state: String?) { + if (state == ProtocolState.OPEN.toString() && autoResubscribe) { + realtimeController.renewSubscriptions() + } } - if (response.error?.id == null - || response.error?.id != "security.token.expired") { - queries[response.requestId]?.completeExceptionally(ApiErrorException(response)) - queries.remove(response.requestId) - return - } - - queries[response.requestId]?.completeExceptionally(ApiErrorException(response)) - protocol.trigger("tokenExpired") - } - - private fun onNetworkStateChange(state: String?) { - if (state == ProtocolState.OPEN.toString() && autoResubscribe) { - realtimeController.renewSubscriptions() + fun connect() { + protocol.connect() } - } - fun connect() { - protocol.connect() - } - - fun disconnect() { - protocol.disconnect() - } - - fun query(query: ConcurrentHashMap): CompletableFuture { - if (protocol.state == ProtocolState.CLOSE) { - throw NotConnectedException() + fun disconnect() { + protocol.disconnect() } - val futureRes: CompletableFuture = CompletableFuture() - val requestId = UUID.randomUUID().toString() - val queryMap = KuzzleMap.from(query) + fun query(query: ConcurrentHashMap): CompletableFuture { + if (protocol.state == ProtocolState.CLOSE) { + throw NotConnectedException() + } - if (query.containsKey("waitForRefresh")) { - if (query["waitForRefresh"] == true) { - queryMap["refresh"] = "wait_for" - } - queryMap.remove("waitForRefresh") - } + val futureRes: CompletableFuture = CompletableFuture() + val requestId = UUID.randomUUID().toString() + val queryMap = KuzzleMap.from(query) - if (authenticationToken != null) { - queryMap["jwt"] = authenticationToken - } + if (query.containsKey("waitForRefresh")) { + if (query["waitForRefresh"] == true) { + queryMap["refresh"] = "wait_for" + } + queryMap.remove("waitForRefresh") + } - queries[requestId] = futureRes - query["requestId"] = requestId + if (authenticationToken != null) { + queryMap["jwt"] = authenticationToken + } - if (!queryMap.containsKey("volatile") || queryMap.isNull("volatile")) { - queryMap["volatile"] = KuzzleMap() - } else if (!queryMap.isMap("volatile")) { - throw Exception(KuzzleExceptionCode.WRONG_VOLATILE_TYPE.toString()) - } + queries[requestId] = futureRes + query["requestId"] = requestId + + if (!queryMap.containsKey("volatile") || queryMap.isNull("volatile")) { + queryMap["volatile"] = KuzzleMap() + } else if (!queryMap.isMap("volatile")) { + throw Exception(KuzzleExceptionCode.WRONG_VOLATILE_TYPE.toString()) + } - queryMap.getMap("volatile")!!["sdkInstanceId"] = instanceId + queryMap.getMap("volatile")!!["sdkInstanceId"] = instanceId - queryMap.getMap("volatile")!!["sdkName"] = sdkName + queryMap.getMap("volatile")!!["sdkName"] = sdkName - protocol.send(query) + protocol.send(query) - return futureRes - } -} \ No newline at end of file + return futureRes + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt index 70ec3c74..2ab644c7 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt @@ -1,236 +1,250 @@ package io.kuzzle.sdk.controllers import io.kuzzle.sdk.Kuzzle +import io.kuzzle.sdk.coreClasses.SearchResult import io.kuzzle.sdk.coreClasses.maps.KuzzleMap import io.kuzzle.sdk.coreClasses.responses.Response -import io.kuzzle.sdk.coreClasses.SearchResult -import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap class AuthController(kuzzle: Kuzzle) : BaseController(kuzzle) { - fun checkRights( - requestPayload: ConcurrentHashMap): CompletableFuture { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "checkRights") - put("body", requestPayload) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> KuzzleMap - .from(response.result as ConcurrentHashMap) - .getBoolean("allowed") as Boolean - } - } - - fun checkToken( - token: String): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "checkToken") - put("body", KuzzleMap().apply { - put("token", token) - }) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } - - fun createMyCredentials( - strategy: String, - credentials: ConcurrentHashMap): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "createMyCredentials") - put("body", credentials) - put("strategy", strategy) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } - - fun credentialsExist(strategy: String): CompletableFuture { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "credentialsExist") - put("strategy", strategy) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as Boolean? } - } - - fun deleteMyCredentials(strategy: String): CompletableFuture { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "deleteMyCredentials") - put("strategy", strategy) - } - return kuzzle.query(query).thenRunAsync {} - } - - fun getCurrentUser(): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "getCurrentUser") - } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap - } - } - - fun getMyCredentials( - strategy: String): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "getMyCredentials") - put("strategy", strategy) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap - } - } - - fun getMyRights(): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "getMyRights") - } - return kuzzle - .query(query) - .thenApplyAsync { response -> - KuzzleMap - .from(response.result as ConcurrentHashMap) - .getArrayList("hits") as ArrayList - } - } - - fun getStrategies(): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "getStrategies") - } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ArrayList } - } - - @JvmOverloads - fun login( - strategy: String, - credentials: ConcurrentHashMap?, - expiresIn: String? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "login") - put("strategy", strategy) - put("body", credentials) - } - if (expiresIn != null) { - query["expiresIn"] = expiresIn - } - return kuzzle.query(query).thenApplyAsync { response -> - val map: KuzzleMap = KuzzleMap - .from(response.result as ConcurrentHashMap) - kuzzle.authenticationToken = map.getString("jwt") - if (map.getString("_id") != null) { - kuzzle.protocol.trigger("loginAttempt", "true") - } else { - kuzzle.protocol.trigger("loginAttempt", "false") - } - map as ConcurrentHashMap - } - } - - fun logout(): CompletableFuture { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "logout") - } - return kuzzle.query(query) - } - - @JvmOverloads - fun refreshToken( - expiresIn: String? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "refreshToken") - put("expiresIn", expiresIn) - } - return kuzzle.query(query).thenApplyAsync { response -> - val map: KuzzleMap = KuzzleMap - .from(response.result as ConcurrentHashMap) - kuzzle.authenticationToken = map.getString("jwt") - map as ConcurrentHashMap - } - } - - @JvmOverloads - fun searchApiKeys( - query: ConcurrentHashMap, - from: Int = 0, - size: Int? = null): CompletableFuture { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "searchApiKeys") - put("body", query) - put("from", from) - put("size", size) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> SearchResult(kuzzle, query, null, from, size, response) } - } - - fun updateMyCredentials( - strategy: String, - credentials: ConcurrentHashMap): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "updateMyCredentials") - put("strategy", strategy) - put("body", credentials) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap - } - } - - fun updateSelf( - content: ConcurrentHashMap): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "updateSelf") - put("body", content) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap - } - } - - fun validateMyCredentials(strategy: String, - credentials: ConcurrentHashMap): CompletableFuture { - val query = KuzzleMap().apply { - put("controller", "auth") - put("action", "validateMyCredentials") - put("strategy", strategy) - put("body", credentials) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as Boolean } - } -} \ No newline at end of file + fun checkRights( + requestPayload: ConcurrentHashMap + ): CompletableFuture { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "checkRights") + put("body", requestPayload) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + KuzzleMap + .from(response.result as ConcurrentHashMap) + .getBoolean("allowed") as Boolean + } + } + + fun checkToken( + token: String + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "checkToken") + put( + "body", + KuzzleMap().apply { + put("token", token) + } + ) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } + } + + fun createMyCredentials( + strategy: String, + credentials: ConcurrentHashMap + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "createMyCredentials") + put("body", credentials) + put("strategy", strategy) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } + } + + fun credentialsExist(strategy: String): CompletableFuture { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "credentialsExist") + put("strategy", strategy) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as Boolean? } + } + + fun deleteMyCredentials(strategy: String): CompletableFuture { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "deleteMyCredentials") + put("strategy", strategy) + } + return kuzzle.query(query).thenRunAsync {} + } + + fun getCurrentUser(): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "getCurrentUser") + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } + } + + fun getMyCredentials( + strategy: String + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "getMyCredentials") + put("strategy", strategy) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } + } + + fun getMyRights(): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "getMyRights") + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + KuzzleMap + .from(response.result as ConcurrentHashMap) + .getArrayList("hits") as ArrayList + } + } + + fun getStrategies(): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "getStrategies") + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ArrayList } + } + + @JvmOverloads + fun login( + strategy: String, + credentials: ConcurrentHashMap?, + expiresIn: String? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "login") + put("strategy", strategy) + put("body", credentials) + } + if (expiresIn != null) { + query["expiresIn"] = expiresIn + } + return kuzzle.query(query).thenApplyAsync { response -> + val map: KuzzleMap = KuzzleMap + .from(response.result as ConcurrentHashMap) + kuzzle.authenticationToken = map.getString("jwt") + if (map.getString("_id") != null) { + kuzzle.protocol.trigger("loginAttempt", "true") + } else { + kuzzle.protocol.trigger("loginAttempt", "false") + } + map as ConcurrentHashMap + } + } + + fun logout(): CompletableFuture { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "logout") + } + return kuzzle.query(query) + } + + @JvmOverloads + fun refreshToken( + expiresIn: String? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "refreshToken") + put("expiresIn", expiresIn) + } + return kuzzle.query(query).thenApplyAsync { response -> + val map: KuzzleMap = KuzzleMap + .from(response.result as ConcurrentHashMap) + kuzzle.authenticationToken = map.getString("jwt") + map as ConcurrentHashMap + } + } + + @JvmOverloads + fun searchApiKeys( + query: ConcurrentHashMap, + from: Int = 0, + size: Int? = null + ): CompletableFuture { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "searchApiKeys") + put("body", query) + put("from", from) + put("size", size) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> SearchResult(kuzzle, query, null, from, size, response) } + } + + fun updateMyCredentials( + strategy: String, + credentials: ConcurrentHashMap + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "updateMyCredentials") + put("strategy", strategy) + put("body", credentials) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } + } + + fun updateSelf( + content: ConcurrentHashMap + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "updateSelf") + put("body", content) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } + } + + fun validateMyCredentials( + strategy: String, + credentials: ConcurrentHashMap + ): CompletableFuture { + val query = KuzzleMap().apply { + put("controller", "auth") + put("action", "validateMyCredentials") + put("strategy", strategy) + put("body", credentials) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as Boolean } + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/BulkController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/BulkController.kt index d0fe9828..86626dee 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/BulkController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/BulkController.kt @@ -2,96 +2,106 @@ package io.kuzzle.sdk.controllers import io.kuzzle.sdk.Kuzzle import io.kuzzle.sdk.coreClasses.maps.KuzzleMap -import io.kuzzle.sdk.coreClasses.responses.Response -import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap -import com.google.gson.internal.LazilyParsedNumber class BulkController(kuzzle: Kuzzle) : BaseController(kuzzle) { -@JvmOverloads - fun deleteByQuery( - index: String, - collection: String, - searchQuery: ConcurrentHashMap, - waitForRefresh: Boolean? = null): CompletableFuture { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "bulk") - put("action", "deleteByQuery") - put("body", ConcurrentHashMap().apply { - put("query", searchQuery) - }) - put("waitForRefresh", waitForRefresh) + @JvmOverloads + fun deleteByQuery( + index: String, + collection: String, + searchQuery: ConcurrentHashMap, + waitForRefresh: Boolean? = null + ): CompletableFuture { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "bulk") + put("action", "deleteByQuery") + put( + "body", + ConcurrentHashMap().apply { + put("query", searchQuery) + } + ) + put("waitForRefresh", waitForRefresh) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> (response.result as ConcurrentHashMap)["deleted"] as Int } } - return kuzzle - .query(query) - .thenApplyAsync { response -> (response.result as ConcurrentHashMap)["deleted"] as Int} - } - fun importData( - index: String, - collection: String, - bulkData: ArrayList>): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "bulk") - put("action", "import") - put("body", ConcurrentHashMap().apply { - put("bulkData", bulkData) - }) + fun importData( + index: String, + collection: String, + bulkData: ArrayList> + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "bulk") + put("action", "import") + put( + "body", + ConcurrentHashMap().apply { + put("bulkData", bulkData) + } + ) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> (response.result as ConcurrentHashMap) } } - return kuzzle - .query(query) - .thenApplyAsync { response -> (response.result as ConcurrentHashMap) } - } -@JvmOverloads - fun mWrite( - index: String, - collection: String, - documents: ArrayList>, - notify: Boolean? = null, - waitForRefresh: Boolean? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "bulk") - put("action", "mWrite") - put("body", ConcurrentHashMap().apply { - put("documents", documents) - }) - put("waitForRefresh", waitForRefresh) - put("notify", notify) + @JvmOverloads + fun mWrite( + index: String, + collection: String, + documents: ArrayList>, + notify: Boolean? = null, + waitForRefresh: Boolean? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "bulk") + put("action", "mWrite") + put( + "body", + ConcurrentHashMap().apply { + put("documents", documents) + } + ) + put("waitForRefresh", waitForRefresh) + put("notify", notify) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> (response.result as ConcurrentHashMap) } } - return kuzzle - .query(query) - .thenApplyAsync { response -> (response.result as ConcurrentHashMap) } - } -@JvmOverloads - fun write( - index: String, - collection: String, - content: ConcurrentHashMap, - id: String? = null, - notify: Boolean? = null, - waitForRefresh: Boolean? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "bulk") - put("action", "write") - put("body", content) - put("waitForRefresh", waitForRefresh) - put("_id", id) - put("notify", notify) + @JvmOverloads + fun write( + index: String, + collection: String, + content: ConcurrentHashMap, + id: String? = null, + notify: Boolean? = null, + waitForRefresh: Boolean? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "bulk") + put("action", "write") + put("body", content) + put("waitForRefresh", waitForRefresh) + put("_id", id) + put("notify", notify) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> (response.result as ConcurrentHashMap) } } - return kuzzle - .query(query) - .thenApplyAsync { response -> (response.result as ConcurrentHashMap) } - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/CollectionController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/CollectionController.kt index aab8a549..1d36a3b2 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/CollectionController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/CollectionController.kt @@ -1,204 +1,227 @@ package io.kuzzle.sdk.controllers import io.kuzzle.sdk.Kuzzle -import io.kuzzle.sdk.coreClasses.maps.KuzzleMap import io.kuzzle.sdk.coreClasses.SearchResult -import java.util.* +import io.kuzzle.sdk.coreClasses.maps.KuzzleMap import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap class CollectionController(kuzzle: Kuzzle) : BaseController(kuzzle) { - @JvmOverloads - fun create( - index: String, - collection: String, - definition: ConcurrentHashMap? = null + @JvmOverloads + fun create( + index: String, + collection: String, + definition: ConcurrentHashMap? = null ): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "create") - put("index", index) - put("collection", collection) - put("definition", definition) - }) - .thenApplyAsync { null } - } + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "create") + put("index", index) + put("collection", collection) + put("definition", definition) + } + ) + .thenApplyAsync { null } + } - fun delete( - index: String, - collection: String + fun delete( + index: String, + collection: String ): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "delete") - put("index", index) - put("collection", collection) - }) - .thenApplyAsync { null } - } + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "delete") + put("index", index) + put("collection", collection) + } + ) + .thenApplyAsync { null } + } - fun deleteSpecifications( - index: String, - collection: String + fun deleteSpecifications( + index: String, + collection: String ): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "deleteSpecifications") - put("index", index) - put("collection", collection) - }) - .thenApplyAsync { null } - } + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "deleteSpecifications") + put("index", index) + put("collection", collection) + } + ) + .thenApplyAsync { null } + } - fun exists( - index: String, - collection: String + fun exists( + index: String, + collection: String ): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "exists") - put("index", index) - put("collection", collection) - }) - .thenApplyAsync { response -> response.result as Boolean } - } + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "exists") + put("index", index) + put("collection", collection) + } + ) + .thenApplyAsync { response -> response.result as Boolean } + } - fun getMapping( - index: String, - collection: String - ): CompletableFuture> { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "getMapping") - put("index", index) - put("collection", collection) - }) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } -} + fun getMapping( + index: String, + collection: String + ): CompletableFuture> { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "getMapping") + put("index", index) + put("collection", collection) + } + ) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } + } -fun getSpecifications( - index: String, - collection: String - ): CompletableFuture> { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "getSpecifications") - put("index", index) - put("collection", collection) - }) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } -} + fun getSpecifications( + index: String, + collection: String + ): CompletableFuture> { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "getSpecifications") + put("index", index) + put("collection", collection) + } + ) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } + } - fun list(index: String): CompletableFuture> { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "list") - put("index", index) - }) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } + fun list(index: String): CompletableFuture> { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "list") + put("index", index) + } + ) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } + } - fun refresh( - index: String, - collection: String - ): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "refresh") - put("index", index) - put("collection", collection) - }) - .thenApplyAsync { null } - } + fun refresh( + index: String, + collection: String + ): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "refresh") + put("index", index) + put("collection", collection) + } + ) + .thenApplyAsync { null } + } - @JvmOverloads - fun searchSpecifications( - searchQuery: ConcurrentHashMap, - scroll: String? = null, - from: Int = 0, - size: Int? = null - ): CompletableFuture { - val query = KuzzleMap().apply { - put("controller", "collection") - put("action", "searchSpecifications") - put("body", searchQuery) - put("from", from) - put("size", size) - put("scroll", scroll) + @JvmOverloads + fun searchSpecifications( + searchQuery: ConcurrentHashMap, + scroll: String? = null, + from: Int = 0, + size: Int? = null + ): CompletableFuture { + val query = KuzzleMap().apply { + put("controller", "collection") + put("action", "searchSpecifications") + put("body", searchQuery) + put("from", from) + put("size", size) + put("scroll", scroll) } - return kuzzle - .query(query) - .thenApplyAsync { response -> SearchResult(kuzzle, query, scroll, from, size, response) } - } + return kuzzle + .query(query) + .thenApplyAsync { response -> SearchResult(kuzzle, query, scroll, from, size, response) } + } - fun truncate( - index: String, - collection: String - ): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "truncate") - put("index", index) - put("collection", collection) - }) - .thenApplyAsync { null } - } - - fun update( - index: String, - collection: String, - definition: ConcurrentHashMap - ): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "update") - put("index", index) - put("collection", collection) - put("body", definition) - }) - .thenApplyAsync { null } - } + fun truncate( + index: String, + collection: String + ): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "truncate") + put("index", index) + put("collection", collection) + } + ) + .thenApplyAsync { null } + } + + fun update( + index: String, + collection: String, + definition: ConcurrentHashMap + ): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "update") + put("index", index) + put("collection", collection) + put("body", definition) + } + ) + .thenApplyAsync { null } + } - fun updateSpecifications( - index: String, - collection: String, - definition: ConcurrentHashMap - ): CompletableFuture> { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "updateSpecifications") - put("index", index) - put("collection", collection) - put("body", definition) - }) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } + fun updateSpecifications( + index: String, + collection: String, + definition: ConcurrentHashMap + ): CompletableFuture> { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "updateSpecifications") + put("index", index) + put("collection", collection) + put("body", definition) + } + ) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } + } - fun validateSpecifications( - index: String, - collection: String, - specifications: ConcurrentHashMap? - ): CompletableFuture> { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "collection") - put("action", "validateSpecifications") - put("index", index) - put("collection", collection) - put("body", specifications) - }) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } -} \ No newline at end of file + fun validateSpecifications( + index: String, + collection: String, + specifications: ConcurrentHashMap? + ): CompletableFuture> { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "collection") + put("action", "validateSpecifications") + put("index", index) + put("collection", collection) + put("body", specifications) + } + ) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/DocumentController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/DocumentController.kt index ac4484bd..2f0d1a16 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/DocumentController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/DocumentController.kt @@ -4,383 +4,404 @@ import com.google.gson.internal.LazilyParsedNumber import io.kuzzle.sdk.Kuzzle import io.kuzzle.sdk.coreClasses.SearchResult import io.kuzzle.sdk.coreClasses.maps.KuzzleMap -import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap class DocumentController(kuzzle: Kuzzle) : BaseController(kuzzle) { - @JvmOverloads - fun count( - index: String, - collection: String, - searchQuery: ConcurrentHashMap = ConcurrentHashMap()): CompletableFuture { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("body", KuzzleMap().put("query", searchQuery)) - put("action", "count") + @JvmOverloads + fun count( + index: String, + collection: String, + searchQuery: ConcurrentHashMap = ConcurrentHashMap() + ): CompletableFuture { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("body", KuzzleMap().put("query", searchQuery)) + put("action", "count") + } + return kuzzle + .query(query) + .thenApplyAsync { response -> ((response.result as ConcurrentHashMap)["count"] as LazilyParsedNumber).toInt() } } - return kuzzle - .query(query) - .thenApplyAsync { response -> ((response.result as ConcurrentHashMap)["count"] as LazilyParsedNumber).toInt() } - } - @JvmOverloads - fun create( - index: String, - collection: String, - document: ConcurrentHashMap, - id: String? = null, - waitForRefresh: Boolean? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "create") - put("body", document) - put("_id", id) - put("waitForRefresh", waitForRefresh) + @JvmOverloads + fun create( + index: String, + collection: String, + document: ConcurrentHashMap, + id: String? = null, + waitForRefresh: Boolean? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + 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 -> response.result as ConcurrentHashMap } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } - @JvmOverloads - fun createOrReplace( - index: String, - collection: String, - id: String, - document: ConcurrentHashMap, - waitForRefresh: Boolean? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "createOrReplace") - put("body", document) - put("_id", id) - put("waitForRefresh", waitForRefresh) + @JvmOverloads + fun createOrReplace( + index: String, + collection: String, + id: String, + document: ConcurrentHashMap, + waitForRefresh: Boolean? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + 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 -> response.result as ConcurrentHashMap } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } - @JvmOverloads - fun delete( - index: String, - collection: String, - id: String?, - waitForRefresh: Boolean? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "delete") - put("_id", id) - put("waitForRefresh", waitForRefresh) - } - - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } + @JvmOverloads + fun delete( + index: String, + collection: String, + id: String?, + waitForRefresh: Boolean? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "delete") + put("_id", id) + put("waitForRefresh", waitForRefresh) + } - @JvmOverloads - fun deleteByQuery( - index: String, - collection: String, - searchQuery: ConcurrentHashMap, - waitForRefresh: Boolean? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "deleteByQuery") - put("body", searchQuery) - put("waitForRefresh", waitForRefresh) + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } } - return kuzzle - .query(query) - .thenApplyAsync { response -> (response.result as ConcurrentHashMap)["ids"] as ArrayList } - } - fun exists( - index: String, - collection: String, - id: String): CompletableFuture { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "exists") - put("_id", id) + @JvmOverloads + fun deleteByQuery( + index: String, + collection: String, + searchQuery: ConcurrentHashMap, + waitForRefresh: Boolean? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "deleteByQuery") + put("body", searchQuery) + put("waitForRefresh", waitForRefresh) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> (response.result as ConcurrentHashMap)["ids"] as ArrayList } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as Boolean } - } - fun get( - index: String, - collection: String, - id: String): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "get") - put("_id", id) + fun exists( + index: String, + collection: String, + id: String + ): CompletableFuture { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "exists") + put("_id", id) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as Boolean } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } - @JvmOverloads - fun mCreate( - index: String, - collection: String, - documents: ArrayList>, - waitForRefresh: Boolean? = null): CompletableFuture>> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "mCreate") - put("body", KuzzleMap().put("documents", documents)) - put("waitForRefresh", waitForRefresh) + fun get( + index: String, + collection: String, + id: String + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "get") + put("_id", id) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap> } - } + @JvmOverloads + fun mCreate( + index: String, + collection: String, + documents: ArrayList>, + waitForRefresh: Boolean? = null + ): CompletableFuture>> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "mCreate") + put("body", KuzzleMap().put("documents", documents)) + put("waitForRefresh", waitForRefresh) + } - @JvmOverloads - fun mCreateOrReplace( - index: String, - collection: String, - documents: ArrayList>, - waitForRefresh: Boolean? = null): CompletableFuture>> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "mCreateOrReplace") - put("body", KuzzleMap().put("documents", documents)) - put("waitForRefresh", waitForRefresh) + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap> } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap> } - } - @JvmOverloads - fun mDelete( - index: String, - collection: String, - ids: ArrayList, - waitForRefresh: Boolean? = null): CompletableFuture>> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "mDelete") - put("waitForRefresh", waitForRefresh) - put("body", KuzzleMap().put("ids", ids)) + @JvmOverloads + fun mCreateOrReplace( + index: String, + collection: String, + documents: ArrayList>, + waitForRefresh: Boolean? = null + ): CompletableFuture>> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "mCreateOrReplace") + put("body", KuzzleMap().put("documents", documents)) + put("waitForRefresh", waitForRefresh) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap> } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap> } - } + @JvmOverloads + fun mDelete( + index: String, + collection: String, + ids: ArrayList, + waitForRefresh: Boolean? = null + ): CompletableFuture>> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "mDelete") + put("waitForRefresh", waitForRefresh) + put("body", KuzzleMap().put("ids", ids)) + } - fun mGet( - index: String, - collection: String, - ids: ArrayList): CompletableFuture>> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "mGet") - put("body", KuzzleMap().put("ids", ids)) + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap> } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap> } - } + fun mGet( + index: String, + collection: String, + ids: ArrayList + ): CompletableFuture>> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "mGet") + put("body", KuzzleMap().put("ids", ids)) + } - @JvmOverloads - fun mReplace( - index: String, - collection: String, - documents: ArrayList>, - waitForRefresh: Boolean? = null): CompletableFuture?>> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "mReplace") - put("body", KuzzleMap().put("documents", documents)) - put("waitForRefresh", waitForRefresh) + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap> } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap?> } - } - @JvmOverloads - fun mUpdate( - index: String, - collection: String, - documents: ArrayList?>, - waitForRefresh: Boolean? = null, - retryOnConflict: Int? = null): CompletableFuture?>> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "mUpdate") - put("body", KuzzleMap().put("documents", documents)) - put("retryOnConflict", retryOnConflict) - put("waitForRefresh", waitForRefresh) + @JvmOverloads + fun mReplace( + index: String, + collection: String, + documents: ArrayList>, + waitForRefresh: Boolean? = null + ): CompletableFuture?>> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "mReplace") + put("body", KuzzleMap().put("documents", documents)) + put("waitForRefresh", waitForRefresh) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap?> } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap?> } - } - @JvmOverloads - fun replace( - index: String, - collection: String, - id: String?, - document: ConcurrentHashMap, - waitForRefresh: Boolean? = null): CompletableFuture> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "replace") - put("body", document) - put("_id", id) - put("waitForRefresh", waitForRefresh) + @JvmOverloads + fun mUpdate( + index: String, + collection: String, + documents: ArrayList?>, + waitForRefresh: Boolean? = null, + retryOnConflict: Int? = null + ): CompletableFuture?>> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "mUpdate") + put("body", KuzzleMap().put("documents", documents)) + put("retryOnConflict", retryOnConflict) + put("waitForRefresh", waitForRefresh) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap?> } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } + @JvmOverloads + fun replace( + index: String, + collection: String, + id: String?, + document: ConcurrentHashMap, + waitForRefresh: Boolean? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "replace") + put("body", document) + put("_id", id) + put("waitForRefresh", waitForRefresh) + } - @JvmOverloads - fun search( - index: String, - collection: String, - searchQuery: ConcurrentHashMap, - scroll: String? = null, - size: Int? = null, - from: Int = 0): CompletableFuture { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "search") - put("body", searchQuery) - put("from", from) - put("size", size) - put("scroll", scroll) - } - if (scroll != null) { - query["scroll"] = scroll + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap } } - return kuzzle - .query(query) - .thenApplyAsync { response -> SearchResult(kuzzle, query, scroll, from, size, response) } - } + @JvmOverloads + fun search( + index: String, + collection: String, + searchQuery: ConcurrentHashMap, + scroll: String? = null, + size: Int? = null, + from: Int = 0 + ): CompletableFuture { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "search") + put("body", searchQuery) + put("from", from) + put("size", size) + put("scroll", scroll) + } + if (scroll != null) { + query["scroll"] = scroll + } - fun search( - index: String, - collection: String, - searchQuery: ConcurrentHashMap, - size: Int? = null, - from: Int = 0): CompletableFuture { + return kuzzle + .query(query) + .thenApplyAsync { response -> SearchResult(kuzzle, query, scroll, from, size, response) } + } - return search(index, collection, searchQuery, null, size, from); - } + fun search( + index: String, + collection: String, + searchQuery: ConcurrentHashMap, + size: Int? = null, + from: Int = 0 + ): CompletableFuture { - @JvmOverloads - fun update( - index: String, - collection: String, - id: String?, - document: ConcurrentHashMap, - waitForRefresh: Boolean? = null, - retryOnConflict: Int? = null, - source: Boolean? = null): CompletableFuture> { - val query = KuzzleMap().apply { - 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 search(index, collection, searchQuery, null, size, from) } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap } - } - @JvmOverloads - fun updateByQuery( - index: String, - collection: String, - searchQuery: ConcurrentHashMap, - changes: ConcurrentHashMap, - waitForRefresh: Boolean? = null, - retryOnConflict: Int? = null, - source: Boolean? = null): CompletableFuture>> { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "updateByQuery") - put("body", KuzzleMap().apply { - put("query", searchQuery) - put("changes", changes) - }) - put("source", source) - put("retryOnConflict", retryOnConflict) - put("waitForRefresh", waitForRefresh) + @JvmOverloads + fun update( + index: String, + collection: String, + id: String?, + document: ConcurrentHashMap, + waitForRefresh: Boolean? = null, + retryOnConflict: Int? = null, + source: Boolean? = null + ): CompletableFuture> { + val query = KuzzleMap().apply { + 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 -> response.result as ConcurrentHashMap } } - return kuzzle - .query(query) - .thenApplyAsync { response -> response.result as ConcurrentHashMap> } - } + @JvmOverloads + fun updateByQuery( + index: String, + collection: String, + searchQuery: ConcurrentHashMap, + changes: ConcurrentHashMap, + waitForRefresh: Boolean? = null, + retryOnConflict: Int? = null, + source: Boolean? = null + ): CompletableFuture>> { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "updateByQuery") + put( + "body", + KuzzleMap().apply { + put("query", searchQuery) + put("changes", changes) + } + ) + put("source", source) + put("retryOnConflict", retryOnConflict) + put("waitForRefresh", waitForRefresh) + } + + return kuzzle + .query(query) + .thenApplyAsync { response -> response.result as ConcurrentHashMap> } + } - fun validate( - index: String, - collection: String, - document: ConcurrentHashMap): CompletableFuture { - val query = KuzzleMap().apply { - put("index", index) - put("collection", collection) - put("controller", "document") - put("action", "validate") - put("body", document) + fun validate( + index: String, + collection: String, + document: ConcurrentHashMap + ): CompletableFuture { + val query = KuzzleMap().apply { + put("index", index) + put("collection", collection) + put("controller", "document") + put("action", "validate") + put("body", document) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> (response.result as ConcurrentHashMap<*, *>)["valid"] as Boolean } } - return kuzzle - .query(query) - .thenApplyAsync { response -> (response.result as ConcurrentHashMap<*, *>)["valid"] as Boolean } - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/IndexController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/IndexController.kt index eb81a743..80ceb277 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/IndexController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/IndexController.kt @@ -2,57 +2,66 @@ package io.kuzzle.sdk.controllers import io.kuzzle.sdk.Kuzzle import io.kuzzle.sdk.coreClasses.maps.KuzzleMap -import java.util.* import java.util.concurrent.CompletableFuture class IndexController(kuzzle: Kuzzle) : BaseController(kuzzle) { - fun create(index: String): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "index") - put("action", "create") - put("index", index) - }) - .thenApplyAsync { null } - } + fun create(index: String): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "index") + put("action", "create") + put("index", index) + } + ) + .thenApplyAsync { null } + } - fun delete(index: String): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "index") - put("action", "delete") - put("index", index) - }) - .thenApplyAsync { null } - } + fun delete(index: String): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "index") + put("action", "delete") + put("index", index) + } + ) + .thenApplyAsync { null } + } - fun exists(index: String): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "index") - put("action", "exists") - put("index", index) - }) - .thenApplyAsync { response -> response.result as Boolean } - } + fun exists(index: String): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "index") + put("action", "exists") + put("index", index) + } + ) + .thenApplyAsync { response -> response.result as Boolean } + } - fun list(): CompletableFuture> { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "index") - put("action", "list") - }) - .thenApplyAsync { response -> (response.result as KuzzleMap).getArrayList("indexes") as ArrayList } - } + fun list(): CompletableFuture> { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "index") + put("action", "list") + } + ) + .thenApplyAsync { response -> (response.result as KuzzleMap).getArrayList("indexes") as ArrayList } + } - fun mDelete(indexes: ArrayList): CompletableFuture> { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "index") - put("action", "mDelete") - put("body", KuzzleMap().put("indexes", indexes)) - }) - .thenApplyAsync { response -> (response.result as KuzzleMap).getArrayList("deleted") as ArrayList } - } -} \ No newline at end of file + fun mDelete(indexes: ArrayList): CompletableFuture> { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "index") + put("action", "mDelete") + put("body", KuzzleMap().put("indexes", indexes)) + } + ) + .thenApplyAsync { response -> (response.result as KuzzleMap).getArrayList("deleted") as ArrayList } + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/RealtimeController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/RealtimeController.kt index 6612a29e..7168240b 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/RealtimeController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/RealtimeController.kt @@ -1,4 +1,4 @@ -package io.kuzzle.sdk.controllers; +package io.kuzzle.sdk.controllers import io.kuzzle.sdk.Kuzzle import io.kuzzle.sdk.coreClasses.json.JsonSerializer @@ -6,183 +6,195 @@ import io.kuzzle.sdk.coreClasses.maps.KuzzleMap import io.kuzzle.sdk.coreClasses.responses.Response import io.kuzzle.sdk.handlers.NotificationHandler import io.kuzzle.sdk.protocol.ProtocolState -import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.function.Consumer class RealtimeController(kuzzle: Kuzzle) : BaseController(kuzzle) { - private inner class Subscription( - val index: String, - val collection: String, - val filter: ConcurrentHashMap, - val handler: (Response) -> Unit, - val scope: String, - val users: String, - val subscribeToSelf: Boolean, - val volatile: ConcurrentHashMap) + private inner class Subscription( + val index: String, + val collection: String, + val filter: ConcurrentHashMap, + val handler: (Response) -> Unit, + val scope: String, + val users: String, + val subscribeToSelf: Boolean, + val volatile: ConcurrentHashMap + ) - init { - kuzzle.protocol.addListener("unhandledResponse") { - val response = Response().apply { - fromMap(JsonSerializer.deserialize(it) as ConcurrentHashMap) - } + init { + kuzzle.protocol.addListener("unhandledResponse") { + val response = Response().apply { + fromMap(JsonSerializer.deserialize(it) as ConcurrentHashMap) + } + + if (response.error != null && response.error!!.id.equals("security.token.expired")) { + kuzzle.protocol.trigger("tokenExpired") + } else { + var sdkInstanceId = "" + if (response.Volatile != null) { + sdkInstanceId = response.Volatile!!["sdkInstanceId"].toString() + } - if (response.error != null && response.error!!.id.equals("security.token.expired")) { - kuzzle.protocol.trigger("tokenExpired") - } else { - var sdkInstanceId = "" - if (response.Volatile != null) { - sdkInstanceId = response.Volatile!!["sdkInstanceId"].toString() + val subs: ArrayList? = currentSubscriptions[response.room] + if (subs != null) { + val instanceId = sdkInstanceId + subs.forEach { + if (instanceId == kuzzle.instanceId && it.subscribeToSelf || instanceId != kuzzle.instanceId) { + it.handler(response) + } + } + } + } } - val subs: ArrayList? = currentSubscriptions[response.room] - if (subs != null) { - val instanceId = sdkInstanceId - subs.forEach { - if (instanceId == kuzzle.instanceId && it.subscribeToSelf || instanceId != kuzzle.instanceId) { - it.handler(response) + kuzzle.protocol.addListener("networkStateChange") { + if (it == ProtocolState.CLOSE.toString()) { + currentSubscriptions.clear() } - } } - } } - kuzzle.protocol.addListener("networkStateChange") { - if (it == ProtocolState.CLOSE.toString()) { - currentSubscriptions.clear() - } + fun count(roomId: String): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "realtime") + put("action", "count") + put("body", KuzzleMap().put("roomId", roomId)) + } + ) + .thenApplyAsync { response -> (response.result as KuzzleMap?)!!.getNumber("count")?.toInt() } } - } - - fun count(roomId: String): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "realtime") - put("action", "count") - put("body", KuzzleMap().put("roomId", roomId)) - }) - .thenApplyAsync { response -> (response.result as KuzzleMap?)!!.getNumber("count")?.toInt() } - } - fun publish(index: String, collection: String, message: ConcurrentHashMap): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "realtime") - put("action", "publish") - put("index", index) - put("collection", collection) - put("body", KuzzleMap().put("message", message)) - }) - .thenApplyAsync { null } - } - - fun renewSubscriptions() { - for ((key, value) in subscriptionsCache) { - (value).forEach(Consumer { subscription: Subscription -> - subscribe( - subscription.index, - subscription.collection, - subscription.filter, - subscription.scope, - subscription.users, - subscription.subscribeToSelf, - subscription.volatile, - subscription.handler - ) - }) - subscriptionsCache[key]!!.clear() + fun publish(index: String, collection: String, message: ConcurrentHashMap): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "realtime") + put("action", "publish") + put("index", index) + put("collection", collection) + put("body", KuzzleMap().put("message", message)) + } + ) + .thenApplyAsync { null } } - } - fun subscribe( - index: String?, - collection: String?, - filters: ConcurrentHashMap, - scope: String = "all", - users: String = "all", - subscribeToSelf: Boolean = true, - volatiles: ConcurrentHashMap = ConcurrentHashMap(), - handler: (Response) -> Unit): CompletableFuture { - val query: KuzzleMap = KuzzleMap().apply { - put("controller", "realtime") - put("action", "subscribe") - put("index", index) - put("collection", collection) - put("body", filters) - put("volatile", volatiles) - } - return kuzzle - .query(query) - .thenApplyAsync { response -> - val channel = (response.result as ConcurrentHashMap<*, *>)["channel"].toString() - val subscription = Subscription( - index!!, - collection!!, - filters, - handler, - scope, - users, - subscribeToSelf, - volatiles) - if (currentSubscriptions[channel] == null) { - val item = ArrayList() - item.add(subscription) - currentSubscriptions[channel] = item - subscriptionsCache[channel] = item - } else { - currentSubscriptions[channel]!!.add(subscription) - subscriptionsCache[channel]!!.add(subscription) - } - (response.result as ConcurrentHashMap<*, *>)["roomId"].toString() + fun renewSubscriptions() { + for ((key, value) in subscriptionsCache) { + (value).forEach( + Consumer { subscription: Subscription -> + subscribe( + subscription.index, + subscription.collection, + subscription.filter, + subscription.scope, + subscription.users, + subscription.subscribeToSelf, + subscription.volatile, + subscription.handler + ) + } + ) + subscriptionsCache[key]!!.clear() } - } + } - /** - For JAVA - */ - @JvmOverloads - fun subscribe( - index: String?, - collection: String?, - filters: ConcurrentHashMap, - scope: String = "all", - users: String = "all", - subscribeToSelf: Boolean = true, - volatiles: ConcurrentHashMap = ConcurrentHashMap(), - handler: NotificationHandler): CompletableFuture { - return subscribe( - index, - collection, - filters, - scope, - users, - subscribeToSelf, - volatiles) { - handler.run(it) + fun subscribe( + index: String?, + collection: String?, + filters: ConcurrentHashMap, + scope: String = "all", + users: String = "all", + subscribeToSelf: Boolean = true, + volatiles: ConcurrentHashMap = ConcurrentHashMap(), + handler: (Response) -> Unit + ): CompletableFuture { + val query: KuzzleMap = KuzzleMap().apply { + put("controller", "realtime") + put("action", "subscribe") + put("index", index) + put("collection", collection) + put("body", filters) + put("volatile", volatiles) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + val channel = (response.result as ConcurrentHashMap<*, *>)["channel"].toString() + val subscription = Subscription( + index!!, + collection!!, + filters, + handler, + scope, + users, + subscribeToSelf, + volatiles + ) + if (currentSubscriptions[channel] == null) { + val item = ArrayList() + item.add(subscription) + currentSubscriptions[channel] = item + subscriptionsCache[channel] = item + } else { + currentSubscriptions[channel]!!.add(subscription) + subscriptionsCache[channel]!!.add(subscription) + } + (response.result as ConcurrentHashMap<*, *>)["roomId"].toString() + } } - } - fun unsubscribe(roomId: String): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "realtime") - put("action", "unsubscribe") - put("body", KuzzleMap().put("roomId", roomId)) - }) - .thenApplyAsync { _ -> - var subs: ArrayList? = currentSubscriptions[roomId] - if (subs != null) { - currentSubscriptions[roomId]!!.clear() - } - subs = subscriptionsCache[roomId] - if (subs != null) { - subscriptionsCache[roomId]!!.clear() - } - null + /** + For JAVA + */ + @JvmOverloads + fun subscribe( + index: String?, + collection: String?, + filters: ConcurrentHashMap, + scope: String = "all", + users: String = "all", + subscribeToSelf: Boolean = true, + volatiles: ConcurrentHashMap = ConcurrentHashMap(), + handler: NotificationHandler + ): CompletableFuture { + return subscribe( + index, + collection, + filters, + scope, + users, + subscribeToSelf, + volatiles + ) { + handler.run(it) } - } + } + + fun unsubscribe(roomId: String): CompletableFuture { + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "realtime") + put("action", "unsubscribe") + put("body", KuzzleMap().put("roomId", roomId)) + } + ) + .thenApplyAsync { _ -> + var subs: ArrayList? = currentSubscriptions[roomId] + if (subs != null) { + currentSubscriptions[roomId]!!.clear() + } + subs = subscriptionsCache[roomId] + if (subs != null) { + subscriptionsCache[roomId]!!.clear() + } + null + } + } - private val currentSubscriptions = ConcurrentHashMap>() - private val subscriptionsCache = ConcurrentHashMap>() + private val currentSubscriptions = ConcurrentHashMap>() + private val subscriptionsCache = ConcurrentHashMap>() } diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/ServerController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/ServerController.kt index 29f48da7..4cc13052 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/ServerController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/ServerController.kt @@ -8,93 +8,95 @@ import java.util.concurrent.ConcurrentHashMap class ServerController(kuzzle: Kuzzle) : BaseController(kuzzle) { - fun adminExists(): CompletableFuture { - val query = KuzzleMap().apply { - put("controller", "server") - put("action", "adminExists") - } - - return kuzzle - .query(query) - .thenApplyAsync { response -> - KuzzleMap - .from(response.result as ConcurrentHashMap) - .getBoolean("exists") + fun adminExists(): CompletableFuture { + val query = KuzzleMap().apply { + put("controller", "server") + put("action", "adminExists") } - } - fun getAllStats(): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "server") - put("action", "getAllStats") + return kuzzle + .query(query) + .thenApplyAsync { response -> + KuzzleMap + .from(response.result as ConcurrentHashMap) + .getBoolean("exists") + } } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap - } - } - fun getConfig(): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "server") - put("action", "getConfig") - } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap + fun getAllStats(): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "server") + put("action", "getAllStats") } - } - - fun getLastStats(): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "server") - put("action", "getLastStats") + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap - } - } - fun getStats(startTime: Date, stopTime: Date): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "server") - put("action", "getStats") - put("startTime", startTime.time) - put("stopTime", stopTime.time) + fun getConfig(): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "server") + put("action", "getConfig") + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap + + fun getLastStats(): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "server") + put("action", "getLastStats") } - } + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } + } - fun info(): CompletableFuture> { - val query = KuzzleMap().apply { - put("controller", "server") - put("action", "info") + fun getStats(startTime: Date, stopTime: Date): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "server") + put("action", "getStats") + put("startTime", startTime.time) + put("stopTime", stopTime.time) + } + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } } - return kuzzle - .query(query) - .thenApplyAsync { response -> - response.result as ConcurrentHashMap + + fun info(): CompletableFuture> { + val query = KuzzleMap().apply { + put("controller", "server") + put("action", "info") } - } + return kuzzle + .query(query) + .thenApplyAsync { response -> + response.result as ConcurrentHashMap + } + } - fun now(): CompletableFuture { + fun now(): CompletableFuture { - return kuzzle - .query(KuzzleMap().apply { - put("controller", "server") - put("action", "now") - }) - .thenApplyAsync { response -> - val date = ((response.result as ConcurrentHashMap)["now"]).toString().toLong() - Date(date) - } - } -} \ No newline at end of file + return kuzzle + .query( + KuzzleMap().apply { + put("controller", "server") + put("action", "now") + } + ) + .thenApplyAsync { response -> + val date = ((response.result as ConcurrentHashMap)["now"]).toString().toLong() + Date(date) + } + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/SearchResult.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/SearchResult.kt index 1b263076..9b6200a8 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/SearchResult.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/SearchResult.kt @@ -3,100 +3,102 @@ package io.kuzzle.sdk.coreClasses import com.google.gson.internal.LazilyParsedNumber import io.kuzzle.sdk.Kuzzle import io.kuzzle.sdk.coreClasses.responses.Response -import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.function.Function class SearchResult { - private var scroll: String? = null - private var from: Int = 0 - private var size: Int? = null - private var request: ConcurrentHashMap? = null - private val scrollAction = "scroll" - private var kuzzle: Kuzzle? = null + private var scroll: String? = null + private var from: Int = 0 + private var size: Int? = null + private var request: ConcurrentHashMap? = null + private val scrollAction = "scroll" + private var kuzzle: Kuzzle? = null - var aggregations: ConcurrentHashMap? = null - @JvmField - public var hits: ArrayList> = ArrayList>() - @JvmField - public var total: Int = 0 - @JvmField - public var fetched: Int = 0 - var scrollId: String? = null + var aggregations: ConcurrentHashMap? = null + @JvmField + public var hits: ArrayList> = ArrayList>() + @JvmField + public var total: Int = 0 + @JvmField + public var fetched: Int = 0 + var scrollId: String? = null - @JvmOverloads - constructor( - kuzzle: Kuzzle?, - request: ConcurrentHashMap?, - scroll: String? = null, - from: Int = 0, - size: Int? = null, - response: Response, - previouslyFetched: Int? = null) { - val _response: ConcurrentHashMap = response.toMap() - this.kuzzle = kuzzle - this.scroll = scroll - this.from = from - this.size = size - this.request = request - this.aggregations = (_response["result"] as ConcurrentHashMap<*, *>)["aggregations"] as ConcurrentHashMap? - this.hits = (_response["result"] as ConcurrentHashMap<*, *>)["hits"] as ArrayList> - this.total = ((_response["result"] as ConcurrentHashMap<*, *>)["total"] as LazilyParsedNumber?)!!.toInt() - this.fetched = hits!!.size - if (previouslyFetched != null) { - this.fetched += previouslyFetched + @JvmOverloads + constructor( + kuzzle: Kuzzle?, + request: ConcurrentHashMap?, + scroll: String? = null, + from: Int = 0, + size: Int? = null, + response: Response, + previouslyFetched: Int? = null + ) { + val _response: ConcurrentHashMap = response.toMap() + this.kuzzle = kuzzle + this.scroll = scroll + this.from = from + this.size = size + this.request = request + this.aggregations = (_response["result"] as ConcurrentHashMap<*, *>)["aggregations"] as ConcurrentHashMap? + this.hits = (_response["result"] as ConcurrentHashMap<*, *>)["hits"] as ArrayList> + this.total = ((_response["result"] as ConcurrentHashMap<*, *>)["total"] as LazilyParsedNumber?)!!.toInt() + this.fetched = hits!!.size + if (previouslyFetched != null) { + this.fetched += previouslyFetched + } + scrollId = (_response["result"] as ConcurrentHashMap<*, *>)["scrollId"] as String? } - scrollId = (_response["result"] as ConcurrentHashMap<*, *>)["scrollId"] as String? - } - private fun getScrollRequest(): ConcurrentHashMap? { - val obj = ConcurrentHashMap() - obj["controller"] = request!!["controller"]!! - obj["action"] = scrollAction - obj["scrollId"] = scrollId!! - return obj - } - - private fun getSearchAfterRequest(): ConcurrentHashMap? { - val nextRequest = request - val lastItem = hits!![hits!!.size] - val searchAfter = ArrayList() - val sort = (request!!["body"] as ConcurrentHashMap<*, *>)["sort"] as ArrayList? - (request!!["body"] as ConcurrentHashMap)["search_after"] = searchAfter - for (value in sort!!) { - var key: String = (value as? String)?.toString() ?: (value as ConcurrentHashMap<*, *>)["First"].toString() - if (key == "_uid") { - searchAfter.add(request!!["collection"].toString() + "#" + lastItem["_id"].toString()) - } else { - val _source = lastItem["_source"] as ConcurrentHashMap<*, *>? - searchAfter.add(_source!![key]) - } + private fun getScrollRequest(): ConcurrentHashMap? { + val obj = ConcurrentHashMap() + obj["controller"] = request!!["controller"]!! + obj["action"] = scrollAction + obj["scrollId"] = scrollId!! + return obj } - return nextRequest - } - operator fun next(): CompletableFuture { - if (fetched >= total) return CompletableFuture.completedFuture(null) - var nextRequest: ConcurrentHashMap? = null - if (scrollId != null) { - nextRequest = getScrollRequest() - } else if (size != null - && (request!!["body"] as ConcurrentHashMap<*, *>)["sort"] != null) { - nextRequest = getSearchAfterRequest() - } else if (size != null) { - if (from != null && from >= total) { - return CompletableFuture.completedFuture(null) - } - from = fetched - nextRequest = request + private fun getSearchAfterRequest(): ConcurrentHashMap? { + val nextRequest = request + val lastItem = hits!![hits!!.size] + val searchAfter = ArrayList() + val sort = (request!!["body"] as ConcurrentHashMap<*, *>)["sort"] as ArrayList? + (request!!["body"] as ConcurrentHashMap)["search_after"] = searchAfter + for (value in sort!!) { + var key: String = (value as? String)?.toString() ?: (value as ConcurrentHashMap<*, *>)["First"].toString() + if (key == "_uid") { + searchAfter.add(request!!["collection"].toString() + "#" + lastItem["_id"].toString()) + } else { + val _source = lastItem["_source"] as ConcurrentHashMap<*, *>? + searchAfter.add(_source!![key]) + } + } + return nextRequest } - if (nextRequest == null) { - return CompletableFuture.completedFuture(null) + + operator fun next(): CompletableFuture { + if (fetched >= total) return CompletableFuture.completedFuture(null) + var nextRequest: ConcurrentHashMap? = null + if (scrollId != null) { + nextRequest = getScrollRequest() + } else if (size != null && + (request!!["body"] as ConcurrentHashMap<*, *>)["sort"] != null + ) { + nextRequest = getSearchAfterRequest() + } else if (size != null) { + if (from != null && from >= total) { + return CompletableFuture.completedFuture(null) + } + from = fetched + nextRequest = request + } + if (nextRequest == null) { + return CompletableFuture.completedFuture(null) + } + val request: ConcurrentHashMap = nextRequest + return kuzzle!!.query(nextRequest) + .thenApplyAsync( + Function { response: Response -> SearchResult(kuzzle, request, scroll, from, size, response, fetched) } + ) } - val request: ConcurrentHashMap = nextRequest - return kuzzle!!.query(nextRequest) - .thenApplyAsync( - Function { response: Response -> SearchResult(kuzzle, request, scroll, from, size, response, fetched) }) - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/ApiErrorException.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/ApiErrorException.kt index 696d8475..c0efe32e 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/ApiErrorException.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/ApiErrorException.kt @@ -1,4 +1,4 @@ -package io.kuzzle.sdk.coreClasses.exceptions; +package io.kuzzle.sdk.coreClasses.exceptions import io.kuzzle.sdk.coreClasses.responses.Response @@ -6,32 +6,32 @@ import io.kuzzle.sdk.coreClasses.responses.Response * Passed to async tasks when an API request returns an error. */ class ApiErrorException : KuzzleException { - companion object { - private const val serialVersionUID = 666379398727075901L - } + companion object { + private const val serialVersionUID = 666379398727075901L + } - /** - * Kuzzle API stack trace - */ - var stack: String? = null - private set + /** + * Kuzzle API stack trace + */ + var stack: String? = null + private set - /** - * Kuzzle API error unique identifier - */ - var id: String? = null - private set + /** + * Kuzzle API error unique identifier + */ + var id: String? = null + private set - /** - * Initializes a new instance of the ApiErrorException - * - * @param response Kuzzle API Response. - */ - constructor(response: Response) : - super(response.error?.message, response.status) { - if (response.error != null) { - this.stack = response.error?.stack; - this.id = response.error?.id; - } - } + /** + * Initializes a new instance of the ApiErrorException + * + * @param response Kuzzle API Response. + */ + constructor(response: Response) : + super(response.error?.message, response.status) { + if (response.error != null) { + this.stack = response.error?.stack + this.id = response.error?.id + } + } } diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/KuzzleException.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/KuzzleException.kt index 73358366..79bcb4d6 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/KuzzleException.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/KuzzleException.kt @@ -4,33 +4,33 @@ package io.kuzzle.sdk.coreClasses.exceptions * Root of all Kuzzle exceptions. */ open class KuzzleException : Exception { - /** - * Kuzzle API error code. - */ - var status: Int - protected set + /** + * Kuzzle API error code. + */ + var status: Int + protected set - /** - * Initializes a new instance of the KuzzleException. - * - * @param message - * Message. - * @param status - * Status. - */ - protected constructor(message: String?, status: Int) : super(message) { - this.status = status - } + /** + * Initializes a new instance of the KuzzleException. + * + * @param message + * Message. + * @param status + * Status. + */ + protected constructor(message: String?, status: Int) : super(message) { + this.status = status + } - protected constructor(message: String?, status: KuzzleExceptionCode) : super(message) { - this.status = status.code - } + protected constructor(message: String?, status: KuzzleExceptionCode) : super(message) { + this.status = status.code + } - protected constructor(status: KuzzleExceptionCode) : super(status.message) { - this.status = status.code - } + protected constructor(status: KuzzleExceptionCode) : super(status.message) { + this.status = status.code + } - companion object { - private const val serialVersionUID = 4446507573441857492L - } -} \ No newline at end of file + companion object { + private const val serialVersionUID = 4446507573441857492L + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/KuzzleExceptionCode.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/KuzzleExceptionCode.kt index 02e6b4fc..396cda40 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/KuzzleExceptionCode.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/KuzzleExceptionCode.kt @@ -1,21 +1,21 @@ package io.kuzzle.sdk.coreClasses.exceptions enum class 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"); + 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" + ); - val code: Int - val message: String? + val code: Int + val message: String? - constructor(code: Int) { - this.code = code - message = null - } + constructor(code: Int) { + this.code = code + message = null + } - constructor(code: Int, message: String?) { - this.code = code - this.message = message - } - -} \ No newline at end of file + constructor(code: Int, message: String?) { + this.code = code + this.message = message + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/NotConnectedException.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/NotConnectedException.kt index b09162cf..d1ba7644 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/NotConnectedException.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/exceptions/NotConnectedException.kt @@ -4,7 +4,7 @@ package io.kuzzle.sdk.coreClasses.exceptions * Thrown when attempting to interact with the network while not connected. */ open class NotConnectedException : KuzzleException { - private val serialVersionUID = 1961824705891656436L + private val serialVersionUID = 1961824705891656436L - constructor() : super(KuzzleExceptionCode.NOT_CONNECTED) -} \ No newline at end of file + constructor() : super(KuzzleExceptionCode.NOT_CONNECTED) +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/json/ConcurrentHashMapTypeAdapter.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/json/ConcurrentHashMapTypeAdapter.kt index 598b0348..88571ec3 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/json/ConcurrentHashMapTypeAdapter.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/json/ConcurrentHashMapTypeAdapter.kt @@ -8,120 +8,119 @@ import com.google.gson.stream.JsonToken import com.google.gson.stream.JsonWriter import io.kuzzle.sdk.coreClasses.maps.KuzzleMap import java.io.IOException -import java.util.* import java.util.concurrent.ConcurrentHashMap class ConcurrentHashMapTypeAdapter : TypeAdapter?>() { - @Throws(IOException::class) - override fun write(out: JsonWriter, map: ConcurrentHashMap?) { - if (map == null) { - out.nullValue() - } else { - out.beginObject() - val iterator = map.entries.iterator() - while (iterator.hasNext()) { - val entry = iterator.next() - out.name(entry.key) - writeObject(out, entry.value) - } - out.endObject() - } - } - - @Throws(IOException::class) - override fun read(`in`: JsonReader): ConcurrentHashMap? { - val peek = `in`.peek() - if (peek == JsonToken.NULL) { - `in`.nextNull() - return null - } else if (peek == JsonToken.BEGIN_OBJECT) { - val map = KuzzleMap() - var key: Any - var value: Any? - `in`.beginObject() - while (`in`.hasNext()) { - key = `in`.nextName() - value = readObject(`in`) - if (!map.containsKey(key)) { - map.put(key, value) + @Throws(IOException::class) + override fun write(out: JsonWriter, map: ConcurrentHashMap?) { + if (map == null) { + out.nullValue() } else { - throw JsonSyntaxException("duplicate key: $key") + out.beginObject() + val iterator = map.entries.iterator() + while (iterator.hasNext()) { + val entry = iterator.next() + out.name(entry.key) + writeObject(out, entry.value) + } + out.endObject() } - } - `in`.endObject() - return map } - return null - } - @Throws(IOException::class) - private fun writeObject(out: JsonWriter, value: Any?) { - if (value is Number) { - out.value(value as Number?) - } else if (value is Boolean) { - out.value(value as Boolean?) - } else if (value is String) { - out.value(value as String?) - } else if (value is ArrayList<*>) { - out.beginArray() - val iterator: Iterator = (value as ArrayList).iterator() - while (iterator.hasNext()) { - writeObject(out, iterator.next()) - } - out.endArray() - } else if (value is ConcurrentHashMap<*, *>) { - out.beginObject() - val iterator: Iterator> = (value as ConcurrentHashMap) - .entries - .iterator() - while (iterator.hasNext()) { - val e = iterator.next() - out.name(e.key) - writeObject(out, e.value) - } - out.endObject() - } else if (value == null) { - out.nullValue() + @Throws(IOException::class) + override fun read(`in`: JsonReader): ConcurrentHashMap? { + val peek = `in`.peek() + if (peek == JsonToken.NULL) { + `in`.nextNull() + return null + } else if (peek == JsonToken.BEGIN_OBJECT) { + val map = KuzzleMap() + var key: Any + var value: Any? + `in`.beginObject() + while (`in`.hasNext()) { + key = `in`.nextName() + value = readObject(`in`) + if (!map.containsKey(key)) { + map.put(key, value) + } else { + throw JsonSyntaxException("duplicate key: $key") + } + } + `in`.endObject() + return map + } + return null } - } - @Throws(IOException::class) - private fun readObject(`in`: JsonReader): Any? { - return when (`in`.peek()) { - JsonToken.NUMBER -> { - val number = `in`.nextString() - LazilyParsedNumber(number) - } - JsonToken.BOOLEAN -> `in`.nextBoolean() - JsonToken.STRING -> `in`.nextString() - JsonToken.NULL -> { - `in`.nextNull() - null - } - JsonToken.BEGIN_ARRAY -> { - val array = ArrayList() - `in`.beginArray() - while (`in`.hasNext()) { - array.add(readObject(`in`)) + @Throws(IOException::class) + private fun writeObject(out: JsonWriter, value: Any?) { + if (value is Number) { + out.value(value as Number?) + } else if (value is Boolean) { + out.value(value as Boolean?) + } else if (value is String) { + out.value(value as String?) + } else if (value is ArrayList<*>) { + out.beginArray() + val iterator: Iterator = (value as ArrayList).iterator() + while (iterator.hasNext()) { + writeObject(out, iterator.next()) + } + out.endArray() + } else if (value is ConcurrentHashMap<*, *>) { + out.beginObject() + val iterator: Iterator> = (value as ConcurrentHashMap) + .entries + .iterator() + while (iterator.hasNext()) { + val e = iterator.next() + out.name(e.key) + writeObject(out, e.value) + } + out.endObject() + } else if (value == null) { + out.nullValue() } - `in`.endArray() - array - } - JsonToken.BEGIN_OBJECT -> { - val map = KuzzleMap() - `in`.beginObject() - while (`in`.hasNext()) { - val key = `in`.nextName() - val `object` = readObject(`in`) - if (`object` != null) { - map.put(key, `object`) - } + } + + @Throws(IOException::class) + private fun readObject(`in`: JsonReader): Any? { + return when (`in`.peek()) { + JsonToken.NUMBER -> { + val number = `in`.nextString() + LazilyParsedNumber(number) + } + JsonToken.BOOLEAN -> `in`.nextBoolean() + JsonToken.STRING -> `in`.nextString() + JsonToken.NULL -> { + `in`.nextNull() + null + } + JsonToken.BEGIN_ARRAY -> { + val array = ArrayList() + `in`.beginArray() + while (`in`.hasNext()) { + array.add(readObject(`in`)) + } + `in`.endArray() + array + } + JsonToken.BEGIN_OBJECT -> { + val map = KuzzleMap() + `in`.beginObject() + while (`in`.hasNext()) { + val key = `in`.nextName() + val `object` = readObject(`in`) + if (`object` != null) { + map.put(key, `object`) + } + } + `in`.endObject() + map + } + JsonToken.END_DOCUMENT, JsonToken.NAME, JsonToken.END_OBJECT, JsonToken.END_ARRAY -> throw IllegalArgumentException() + else -> throw IllegalArgumentException() } - `in`.endObject() - map - } - JsonToken.END_DOCUMENT, JsonToken.NAME, JsonToken.END_OBJECT, JsonToken.END_ARRAY -> throw IllegalArgumentException() - else -> throw IllegalArgumentException() } - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/json/JsonSerializer.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/json/JsonSerializer.kt index 246eb865..1cc31bae 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/json/JsonSerializer.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/json/JsonSerializer.kt @@ -5,22 +5,24 @@ import com.google.gson.GsonBuilder import java.util.concurrent.ConcurrentHashMap object JsonSerializer { - private var gson: Gson? = null - fun deserialize(rawJson: String?): ConcurrentHashMap<*, *> { - return gson!!.fromJson(rawJson, ConcurrentHashMap::class.java) - } + private var gson: Gson? = null + fun deserialize(rawJson: String?): ConcurrentHashMap<*, *> { + return gson!!.fromJson(rawJson, ConcurrentHashMap::class.java) + } - fun serialize(map: ConcurrentHashMap?): String { - return gson!!.toJson(map, ConcurrentHashMap::class.java) - } + fun serialize(map: ConcurrentHashMap?): String { + return gson!!.toJson(map, ConcurrentHashMap::class.java) + } - init { - gson = GsonBuilder() - .disableHtmlEscaping() - .disableInnerClassSerialization() - .serializeNulls() - .registerTypeAdapter(ConcurrentHashMap::class.java, - ConcurrentHashMapTypeAdapter()) - .create() - } -} \ No newline at end of file + init { + gson = GsonBuilder() + .disableHtmlEscaping() + .disableInnerClassSerialization() + .serializeNulls() + .registerTypeAdapter( + ConcurrentHashMap::class.java, + ConcurrentHashMapTypeAdapter() + ) + .create() + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/KuzzleMap.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/KuzzleMap.kt index eb903e58..24ebae66 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/KuzzleMap.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/KuzzleMap.kt @@ -1,6 +1,5 @@ package io.kuzzle.sdk.coreClasses.maps -import java.util.* import java.util.concurrent.ConcurrentHashMap /** @@ -9,239 +8,239 @@ import java.util.concurrent.ConcurrentHashMap * manipulate them. */ class KuzzleMap : ConcurrentHashMap { - /** - * Create a new instance of CustomMap - */ - constructor() : super() {} - - /** - * Create a new instance of CustomMap from a ConcurrentHashMap, - * Object>. - * - * @param map - * ConcurrentHashMap, Object> representing JSON. - */ - constructor(map: ConcurrentHashMap) : super() { - val it = map.entries.iterator() - while (it.hasNext()) { - val entry = it.next() - this[entry.key] = entry.value - } - } - - fun put(s: String, o: Any?): KuzzleMap? { - if (o != null) { - super.put(s, o) - } - return this - } - - override operator fun get(key: String?): Any? { - val value = super.get(key) - return if (value is Null) { - null - } else value - } - - /** - * Check whether the key value is null or not. - * - * @param key - * a String representing the key. - * @return true if the value is null. - */ - fun isNull(key: String): Boolean { - return super.get(key) is 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. - */ - fun isString(key: String): Boolean { - return super.get(key) is 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. - */ - fun isBoolean(key: String): Boolean { - return super.get(key) is 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. - */ - fun isNumber(key: String): Boolean { - return super.get(key) is 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. - */ - fun isArrayList(key: String): Boolean { - return super.get(key) is 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. - */ - fun isMap(key: String): Boolean { - return super.get(key) is 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 - */ - fun getString(key: String): String? { - return if (isString(key)) super.get(key) as String else 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 - */ - fun getBoolean(key: String): Boolean? { - return if (isBoolean(key)) super.get(key) as Boolean? else 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 - */ - fun getNumber(key: String): Number? { - return if (isNumber(key)) super.get(key) as Number? else 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 - */ - fun getArrayList(key: String): ArrayList<*>? { - return if (isArrayList(key)) super.get(key) as ArrayList<*>? else 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 - */ - fun getMap(key: String): KuzzleMap? { - return if (isMap(key)) from(super.get(key) as ConcurrentHashMap) else 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 - */ - fun optString(key: String, def: String): String { - return if (isString(key)) super.get(key) as String else 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 - */ - fun optBoolean(key: String, def: Boolean?): Boolean? { - return if (isBoolean(key)) super.get(key) as Boolean? else 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 - */ - fun optNumber(key: String, def: Number?): Number? { - return if (isNumber(key)) super.get(key) as Number? else 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 - */ - fun optArrayList(key: String, def: ArrayList<*>?): ArrayList<*>? { - return if (isArrayList(key)) super.get(key) as ArrayList<*>? else 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 - */ - fun optMap(key: String, def: ConcurrentHashMap): KuzzleMap { - return if (isMap(key)) from(super.get(key) as ConcurrentHashMap) else from(def) - } - - companion object { - /** - * serialVersionUID - */ - private const val serialVersionUID = -3027862451021177820L - - /** - * Convert à ConcurrentHashMap, Object> to a CustomMap + /** + * Create a new instance of CustomMap + */ + constructor() : super() {} + + /** + * Create a new instance of CustomMap from a ConcurrentHashMap, + * Object>. * * @param map * ConcurrentHashMap, Object> representing JSON. - * @return a CustomMap instance */ - fun from(map: ConcurrentHashMap): KuzzleMap { - return if (map is KuzzleMap) { - map - } else KuzzleMap(map) + constructor(map: ConcurrentHashMap) : super() { + val it = map.entries.iterator() + while (it.hasNext()) { + val entry = it.next() + this[entry.key] = entry.value + } + } + + fun put(s: String, o: Any?): KuzzleMap? { + if (o != null) { + super.put(s, o) + } + return this + } + + override operator fun get(key: String?): Any? { + val value = super.get(key) + return if (value is Null) { + null + } else value + } + + /** + * Check whether the key value is null or not. + * + * @param key + * a String representing the key. + * @return true if the value is null. + */ + fun isNull(key: String): Boolean { + return super.get(key) is 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. + */ + fun isString(key: String): Boolean { + return super.get(key) is 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. + */ + fun isBoolean(key: String): Boolean { + return super.get(key) is 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. + */ + fun isNumber(key: String): Boolean { + return super.get(key) is 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. + */ + fun isArrayList(key: String): Boolean { + return super.get(key) is 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. + */ + fun isMap(key: String): Boolean { + return super.get(key) is 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 + */ + fun getString(key: String): String? { + return if (isString(key)) super.get(key) as String else 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 + */ + fun getBoolean(key: String): Boolean? { + return if (isBoolean(key)) super.get(key) as Boolean? else 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 + */ + fun getNumber(key: String): Number? { + return if (isNumber(key)) super.get(key) as Number? else 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 + */ + fun getArrayList(key: String): ArrayList<*>? { + return if (isArrayList(key)) super.get(key) as ArrayList<*>? else 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 + */ + fun getMap(key: String): KuzzleMap? { + return if (isMap(key)) from(super.get(key) as ConcurrentHashMap) else 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 + */ + fun optString(key: String, def: String): String { + return if (isString(key)) super.get(key) as String else 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 + */ + fun optBoolean(key: String, def: Boolean?): Boolean? { + return if (isBoolean(key)) super.get(key) as Boolean? else 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 + */ + fun optNumber(key: String, def: Number?): Number? { + return if (isNumber(key)) super.get(key) as Number? else 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 + */ + fun optArrayList(key: String, def: ArrayList<*>?): ArrayList<*>? { + return if (isArrayList(key)) super.get(key) as ArrayList<*>? else 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 + */ + fun optMap(key: String, def: ConcurrentHashMap): KuzzleMap { + return if (isMap(key)) from(super.get(key) as ConcurrentHashMap) else from(def) + } + + companion object { + /** + * serialVersionUID + */ + private const val serialVersionUID = -3027862451021177820L + + /** + * Convert à ConcurrentHashMap, Object> to a CustomMap + * + * @param map + * ConcurrentHashMap, Object> representing JSON. + * @return a CustomMap instance + */ + fun from(map: ConcurrentHashMap): KuzzleMap { + return if (map is KuzzleMap) { + map + } else KuzzleMap(map) + } } - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/Null.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/Null.kt index 29330a5e..53dafb6f 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/Null.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/Null.kt @@ -1,12 +1,12 @@ package io.kuzzle.sdk.coreClasses.maps class Null { - val hashCode = 572487463 - override fun hashCode(): Int { - return hashCode - } + val hashCode = 572487463 + override fun hashCode(): Int { + return hashCode + } - override fun toString(): String { - return "null" - } -} \ No newline at end of file + override fun toString(): String { + return "null" + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/Serializable.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/Serializable.kt index a1215912..d8c998ca 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/Serializable.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/maps/Serializable.kt @@ -3,9 +3,9 @@ package io.kuzzle.sdk.coreClasses.maps import java.util.concurrent.ConcurrentHashMap interface Serializable { - @Throws(Exception::class) - fun fromMap(map: ConcurrentHashMap?) + @Throws(Exception::class) + fun fromMap(map: ConcurrentHashMap?) - @Throws(Exception::class) - fun toMap(): ConcurrentHashMap? -} \ No newline at end of file + @Throws(Exception::class) + fun toMap(): ConcurrentHashMap? +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/responses/ErrorResponse.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/responses/ErrorResponse.kt index 22519743..9e2a3504 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/responses/ErrorResponse.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/responses/ErrorResponse.kt @@ -5,41 +5,41 @@ import io.kuzzle.sdk.coreClasses.maps.Serializable import java.util.concurrent.ConcurrentHashMap class ErrorResponse : Serializable { - /** - * Response status, following HTTP status codes. - */ - var status = 0 + /** + * Response status, following HTTP status codes. + */ + var status = 0 - /** - * Error message - */ - var message: String? = null + /** + * Error message + */ + var message: String? = null - /** - * Error ID - */ - var id: String? = null + /** + * Error ID + */ + var id: String? = null - /** - * Error stack - */ - var stack: String? = null + /** + * Error stack + */ + var stack: String? = null - override fun fromMap(map: ConcurrentHashMap?) { - if (map == null) return - val kuzzleMap: KuzzleMap? = KuzzleMap?.from(map) - status = kuzzleMap?.optNumber("status", 0)!!.toInt() - message = kuzzleMap?.getString("message") - stack = kuzzleMap?.getString("stack") - id = kuzzleMap?.getString("id") - } + override fun fromMap(map: ConcurrentHashMap?) { + if (map == null) return + val kuzzleMap: KuzzleMap? = KuzzleMap?.from(map) + status = kuzzleMap?.optNumber("status", 0)!!.toInt() + message = kuzzleMap?.getString("message") + stack = kuzzleMap?.getString("stack") + id = kuzzleMap?.getString("id") + } - override fun toMap(): ConcurrentHashMap { - val map: ConcurrentHashMap = KuzzleMap() - map["status"] = status - map["message"] = message!! - map["stack"] = stack!! - map["id"] = id!! - return map - } -} \ No newline at end of file + override fun toMap(): ConcurrentHashMap { + val map: ConcurrentHashMap = KuzzleMap() + map["status"] = status + map["message"] = message!! + map["stack"] = stack!! + map["id"] = id!! + return map + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/coreClasses/responses/Response.kt b/src/main/kotlin/io/kuzzle/sdk/coreClasses/responses/Response.kt index 684bb5cf..8fe61f81 100644 --- a/src/main/kotlin/io/kuzzle/sdk/coreClasses/responses/Response.kt +++ b/src/main/kotlin/io/kuzzle/sdk/coreClasses/responses/Response.kt @@ -6,137 +6,137 @@ import io.kuzzle.sdk.coreClasses.maps.Serializable import java.util.concurrent.ConcurrentHashMap class Response : Serializable { - var mapResponse: ConcurrentHashMap? = null - private set - - var room: String? = null - - /** - * Response payload (depends on the executed API action) - */ - var result: Any? = null - - /** - * Error object (null if the request finished successfully) - */ - var error: ErrorResponse? = null - - /** - * Request unique identifier. - */ - var requestId: String? = null - - /** - * Response status, following HTTP status codes - */ - var status = 0 - - /** - * Executed Kuzzle API controller - */ - var controller: String? = null - - /** - * Executed Kuzzle API controller's action. - */ - var action: String? = null - - /** - * Impacted data index. - */ - var index: String? = null - - /** - * Impacted data collection. - */ - var collection: String? = null - - /** - * Volatile data. - */ - var Volatile: ConcurrentHashMap? = null - // The following properties are specific to real-time notifications - /** - * Network protocol at the origin of the real-time notification. - */ - var protocol: String? = null - - /** - * Document scope ("in" or "out") - */ - var scope: String? = null - - /** - * Document state - */ - var state: String? = null - - /** - * Notification timestamp (UTC) - */ - var timestamp: Long? = null - - /** - * Notification type - */ - var type: String? = null - - override fun fromMap(map: ConcurrentHashMap?) { - if (map == null) return - - mapResponse = map - - val kuzzleMap = KuzzleMap(map) - room = kuzzleMap.getString("room") - result = kuzzleMap.get("result") - error = null; - if (kuzzleMap.isMap("error")) { - error = ErrorResponse() - error!!.fromMap(kuzzleMap.getMap("error")) + var mapResponse: ConcurrentHashMap? = null + private set + + var room: String? = null + + /** + * Response payload (depends on the executed API action) + */ + var result: Any? = null + + /** + * Error object (null if the request finished successfully) + */ + var error: ErrorResponse? = null + + /** + * Request unique identifier. + */ + var requestId: String? = null + + /** + * Response status, following HTTP status codes + */ + var status = 0 + + /** + * Executed Kuzzle API controller + */ + var controller: String? = null + + /** + * Executed Kuzzle API controller's action. + */ + var action: String? = null + + /** + * Impacted data index. + */ + var index: String? = null + + /** + * Impacted data collection. + */ + var collection: String? = null + + /** + * Volatile data. + */ + var Volatile: ConcurrentHashMap? = null + // The following properties are specific to real-time notifications + /** + * Network protocol at the origin of the real-time notification. + */ + var protocol: String? = null + + /** + * Document scope ("in" or "out") + */ + var scope: String? = null + + /** + * Document state + */ + var state: String? = null + + /** + * Notification timestamp (UTC) + */ + var timestamp: Long? = null + + /** + * Notification type + */ + var type: String? = null + + override fun fromMap(map: ConcurrentHashMap?) { + if (map == null) return + + mapResponse = map + + val kuzzleMap = KuzzleMap(map) + room = kuzzleMap.getString("room") + result = kuzzleMap.get("result") + error = null + if (kuzzleMap.isMap("error")) { + error = ErrorResponse() + error!!.fromMap(kuzzleMap.getMap("error")) + } + requestId = kuzzleMap.getString("requestId") + if (requestId == null) { + throw Exception(KuzzleExceptionCode.MISSING_REQUESTID.message) + } + status = (kuzzleMap.optNumber("status", 0) as com.google.gson.internal.LazilyParsedNumber).toInt() + controller = kuzzleMap.getString("controller") + action = kuzzleMap.getString("action") + index = kuzzleMap.getString("index") + collection = kuzzleMap.getString("collection") + Volatile = kuzzleMap.optMap("volatile", ConcurrentHashMap()) + protocol = kuzzleMap.getString("protocol") + scope = kuzzleMap.getString("scope") + state = kuzzleMap.getString("state") + timestamp = when (kuzzleMap.getNumber("timestamp")) { + null -> null + else -> (kuzzleMap.getNumber("timestamp") as com.google.gson.internal.LazilyParsedNumber).toLong() + } + type = kuzzleMap.getString("type") } - requestId = kuzzleMap.getString("requestId") - if (requestId == null) { - throw Exception(KuzzleExceptionCode.MISSING_REQUESTID.message) + + override fun toMap(): ConcurrentHashMap { + val map = ConcurrentHashMap() + + room?.let { map.put("room", it) } + result?.let { map.put("result", it) } + error?.let { map.put("error", it) } + requestId?.let { map.put("requestId", it) } + map.put("status", status) + controller?.let { map.put("controller", it) } + action?.let { map.put("action", it) } + index?.let { map.put("index", it) } + collection?.let { map.put("collection", it) } + Volatile?.let { map.put("volatile", it) } + protocol?.let { map.put("protocol", it) } + scope?.let { map.put("scope", it) } + map.put("status", status) + timestamp?.let { map.put("timestamp", it) } + type?.let { map.put("type", it) } + + return map } - status = (kuzzleMap.optNumber("status", 0) as com.google.gson.internal.LazilyParsedNumber).toInt() - controller = kuzzleMap.getString("controller") - action = kuzzleMap.getString("action") - index = kuzzleMap.getString("index") - collection = kuzzleMap.getString("collection") - Volatile = kuzzleMap.optMap("volatile", ConcurrentHashMap()) - protocol = kuzzleMap.getString("protocol") - scope = kuzzleMap.getString("scope") - state = kuzzleMap.getString("state") - timestamp = when(kuzzleMap.getNumber("timestamp")) { - null -> null - else -> (kuzzleMap.getNumber("timestamp") as com.google.gson.internal.LazilyParsedNumber).toLong() + + override fun toString(): String { + return mapResponse.toString() } - type = kuzzleMap.getString("type") - } - - override fun toMap(): ConcurrentHashMap { - val map = ConcurrentHashMap() - - room?.let { map.put("room", it) } - result?.let { map.put("result", it) } - error?.let { map.put("error", it) } - requestId?.let { map.put("requestId", it) } - map.put("status", status) - controller?.let { map.put("controller", it) } - action?.let { map.put("action", it) } - index?.let { map.put("index", it) } - collection?.let { map.put("collection", it) } - Volatile?.let { map.put("volatile", it) } - protocol?.let { map.put("protocol", it) } - scope?.let { map.put("scope", it) } - map.put("status", status) - timestamp?.let { map.put("timestamp", it) } - type?.let { map.put("type", it) } - - return map - } - - override fun toString(): String { - return mapResponse.toString() - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/io/kuzzle/sdk/events/EventManager.kt b/src/main/kotlin/io/kuzzle/sdk/events/EventManager.kt index cc25265b..ae562fe1 100644 --- a/src/main/kotlin/io/kuzzle/sdk/events/EventManager.kt +++ b/src/main/kotlin/io/kuzzle/sdk/events/EventManager.kt @@ -1,13 +1,13 @@ package io.kuzzle.sdk.events open class EventManager { - private val listeners: HashMap Unit> = HashMap() + private val listeners: HashMap Unit> = HashMap() - fun addListener(event: String, listener: (String?) -> Unit) { - listeners[event] = listener - } + fun addListener(event: String, listener: (String?) -> Unit) { + listeners[event] = listener + } - fun trigger(event: String, message: String? = null) { - listeners[event]?.invoke(message) - } -} \ No newline at end of file + fun trigger(event: String, message: String? = null) { + listeners[event]?.invoke(message) + } +} diff --git a/src/main/kotlin/io/kuzzle/sdk/handlers/NotificationHandler.kt b/src/main/kotlin/io/kuzzle/sdk/handlers/NotificationHandler.kt index 0e9e71bd..9e08f04e 100644 --- a/src/main/kotlin/io/kuzzle/sdk/handlers/NotificationHandler.kt +++ b/src/main/kotlin/io/kuzzle/sdk/handlers/NotificationHandler.kt @@ -7,5 +7,5 @@ import io.kuzzle.sdk.coreClasses.responses.Response * to make it more usable in JAVA */ interface NotificationHandler { - fun run(notification: Response) + fun run(notification: Response) } diff --git a/src/main/kotlin/io/kuzzle/sdk/protocol/AbstractProtocol.kt b/src/main/kotlin/io/kuzzle/sdk/protocol/AbstractProtocol.kt index e5b82fc6..67179f6d 100644 --- a/src/main/kotlin/io/kuzzle/sdk/protocol/AbstractProtocol.kt +++ b/src/main/kotlin/io/kuzzle/sdk/protocol/AbstractProtocol.kt @@ -3,9 +3,9 @@ package io.kuzzle.sdk.protocol import io.kuzzle.sdk.events.EventManager import java.util.concurrent.ConcurrentHashMap -abstract class AbstractProtocol: EventManager() { - abstract var state: ProtocolState - abstract fun connect() - abstract fun disconnect() - abstract fun send(payload: ConcurrentHashMap) +abstract class AbstractProtocol : EventManager() { + abstract var state: ProtocolState + abstract fun connect() + abstract fun disconnect() + abstract fun send(payload: ConcurrentHashMap) } diff --git a/src/main/kotlin/io/kuzzle/sdk/protocol/ProtocolState.kt b/src/main/kotlin/io/kuzzle/sdk/protocol/ProtocolState.kt index a3c38211..0d5476cc 100644 --- a/src/main/kotlin/io/kuzzle/sdk/protocol/ProtocolState.kt +++ b/src/main/kotlin/io/kuzzle/sdk/protocol/ProtocolState.kt @@ -1,7 +1,7 @@ package io.kuzzle.sdk.protocol enum class ProtocolState { - CLOSE, // The network protocol does not accept requests. - OPEN, // The network protocol accepts new requests. - RECONNECTING // The nerwork protocol is trying to reconnect -} \ No newline at end of file + CLOSE, // The network protocol does not accept requests. + OPEN, // The network protocol accepts new requests. + RECONNECTING // The nerwork protocol is trying to reconnect +} diff --git a/src/main/kotlin/io/kuzzle/sdk/protocol/WebSocket.kt b/src/main/kotlin/io/kuzzle/sdk/protocol/WebSocket.kt index 5007c139..9922982b 100644 --- a/src/main/kotlin/io/kuzzle/sdk/protocol/WebSocket.kt +++ b/src/main/kotlin/io/kuzzle/sdk/protocol/WebSocket.kt @@ -25,135 +25,136 @@ import java.util.concurrent.ConcurrentLinkedQueue import kotlin.concurrent.thread open class WebSocket : AbstractProtocol { - protected open var ws: DefaultClientWebSocketSession? = null - private val host: String - private val port: Int - private val isSsl: Boolean - private val queue: ConcurrentLinkedQueue = ConcurrentLinkedQueue() - override var state: ProtocolState = ProtocolState.CLOSE - private val autoReconnect: Boolean - private val reconnectionDelay: Long - private val reconnectionRetries: Long - private var retryCount: Long = 0 + protected open var ws: DefaultClientWebSocketSession? = null + private val host: String + private val port: Int + private val isSsl: Boolean + private val queue: ConcurrentLinkedQueue = ConcurrentLinkedQueue() + override var state: ProtocolState = ProtocolState.CLOSE + private val autoReconnect: Boolean + private val reconnectionDelay: Long + private val reconnectionRetries: Long + private var retryCount: Long = 0 - @KtorExperimentalAPI - protected open var client = HttpClient { - install(WebSockets) - install(JsonFeature) { - serializer = GsonSerializer() - acceptContentTypes += ContentType("application", "json") + @KtorExperimentalAPI + protected open var client = HttpClient { + install(WebSockets) + install(JsonFeature) { + serializer = GsonSerializer() + acceptContentTypes += ContentType("application", "json") + } } - } - - @JvmOverloads - constructor( - host: String, - port: Int = 7512, - isSsl: Boolean = false, - autoReconnect: Boolean = true, - reconnectionDelay: Long = 1000, - reconnectionRetries: Long = 60) { - this.host = host - this.port = port - this.isSsl = isSsl - this.autoReconnect = autoReconnect - this.reconnectionDelay = reconnectionDelay - this.reconnectionRetries = reconnectionRetries - } - private fun tryToReconnect() { - if (retryCount < reconnectionRetries) { - retryCount++ - state = ProtocolState.RECONNECTING - trigger("networkStateChange", state.toString()) - Thread.sleep(reconnectionDelay) - thread(start = true) { - connect() - } + @JvmOverloads + constructor( + host: String, + port: Int = 7512, + isSsl: Boolean = false, + autoReconnect: Boolean = true, + reconnectionDelay: Long = 1000, + reconnectionRetries: Long = 60 + ) { + this.host = host + this.port = port + this.isSsl = isSsl + this.autoReconnect = autoReconnect + this.reconnectionDelay = reconnectionDelay + this.reconnectionRetries = reconnectionRetries } - } - @KtorExperimentalAPI - override fun connect() { - val wait = CompletableFuture() - val block: suspend DefaultClientWebSocketSession.() -> Unit = { - ws = this - // @TODO Create enums for events - state = ProtocolState.OPEN - trigger("networkStateChange", ProtocolState.OPEN.toString()) - thread(start = true) { - while (ws != null) { - val payload = queue.poll() - if (payload != null) { - GlobalScope.launch { - ws?.send(Frame.Text(payload)) + private fun tryToReconnect() { + if (retryCount < reconnectionRetries) { + retryCount++ + state = ProtocolState.RECONNECTING + trigger("networkStateChange", state.toString()) + Thread.sleep(reconnectionDelay) + thread(start = true) { + connect() } - } - } - } - wait.complete(null) - try { - for (frame in incoming) { - when (frame) { - // @TODO Create enums for events - is Frame.Text -> super.trigger("messageReceived", frame.readText()) - // @TODO Create enums for events - is Frame.Binary -> super.trigger("messageReceived", frame.readBytes().toString()) - } } - } catch (e: Exception) { - tryToReconnect() - } - state = ProtocolState.CLOSE - trigger("networkStateChange", ProtocolState.CLOSE.toString()) - ws = null } - GlobalScope.launch { - try { - if (isSsl) { - client.wss( - host = this@WebSocket.host, - port = this@WebSocket.port, - block = block - ) - } else { - client.ws( - host = this@WebSocket.host, - port = this@WebSocket.port, - block = block - ) - } - retryCount = 0 - // This thread is here to let JAVA run until the socket is closed - // In Kotlin this is handled by the block function above but for some reason in JAVA it is - // non blocking. - thread(start = true) { - while (true) {} - } - } catch (e: Exception) { - when (e) { - is ConnectException, - is SocketException, - is IOException -> { - tryToReconnect() + + @KtorExperimentalAPI + override fun connect() { + val wait = CompletableFuture() + val block: suspend DefaultClientWebSocketSession.() -> Unit = { + ws = this + // @TODO Create enums for events + state = ProtocolState.OPEN + trigger("networkStateChange", ProtocolState.OPEN.toString()) + thread(start = true) { + while (ws != null) { + val payload = queue.poll() + if (payload != null) { + GlobalScope.launch { + ws?.send(Frame.Text(payload)) + } + } + } + } wait.complete(null) - } else -> throw e + try { + for (frame in incoming) { + when (frame) { + // @TODO Create enums for events + is Frame.Text -> super.trigger("messageReceived", frame.readText()) + // @TODO Create enums for events + is Frame.Binary -> super.trigger("messageReceived", frame.readBytes().toString()) + } + } + } catch (e: Exception) { + tryToReconnect() + } + state = ProtocolState.CLOSE + trigger("networkStateChange", ProtocolState.CLOSE.toString()) + ws = null } - } + GlobalScope.launch { + try { + if (isSsl) { + client.wss( + host = this@WebSocket.host, + port = this@WebSocket.port, + block = block + ) + } else { + client.ws( + host = this@WebSocket.host, + port = this@WebSocket.port, + block = block + ) + } + retryCount = 0 + // This thread is here to let JAVA run until the socket is closed + // In Kotlin this is handled by the block function above but for some reason in JAVA it is + // non blocking. + thread(start = true) { + while (true) {} + } + } catch (e: Exception) { + when (e) { + is ConnectException, + is SocketException, + is IOException -> { + tryToReconnect() + wait.complete(null) + } else -> throw e + } + } + } + wait.get() } - wait.get() - } - override fun disconnect() { - state = ProtocolState.CLOSE - trigger("networkStateChange", ProtocolState.CLOSE.toString()) - GlobalScope.launch { - ws?.close() - ws = null + override fun disconnect() { + state = ProtocolState.CLOSE + trigger("networkStateChange", ProtocolState.CLOSE.toString()) + GlobalScope.launch { + ws?.close() + ws = null + } } - } - override fun send(payload: ConcurrentHashMap) { - queue.add(JsonSerializer.serialize(payload)) - } -} \ No newline at end of file + override fun send(payload: ConcurrentHashMap) { + queue.add(JsonSerializer.serialize(payload)) + } +} diff --git a/src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt b/src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt index 57e88c9a..b66cde22 100644 --- a/src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt +++ b/src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt @@ -11,73 +11,71 @@ import io.ktor.http.headersOf import io.ktor.util.KtorExperimentalAPI import io.kuzzle.sdk.protocol.ProtocolState import io.kuzzle.sdk.protocol.WebSocket -import org.junit.Assert.* import org.junit.Before import org.junit.Test import java.util.concurrent.ConcurrentHashMap class WebSocketTests { - inner class MockedSocket(host: String) : WebSocket(host) { - @KtorExperimentalAPI - var mockedClient: HttpClient - get() = super.client - set(value) { - super.client = value - } - } + inner class MockedSocket(host: String) : WebSocket(host) { + @KtorExperimentalAPI + var mockedClient: HttpClient + get() = super.client + set(value) { + super.client = value + } + } - private var socket: MockedSocket? = null + private var socket: MockedSocket? = null - @KtorExperimentalAPI - @Before - fun setup() { - socket = MockedSocket("localhost") - socket?.mockedClient = HttpClient(MockEngine) { - install(JsonFeature) { - serializer = GsonSerializer() - acceptContentTypes += ContentType("application", "json") - } - engine { - addHandler { request -> - when (request.url.toString()) { - "ws://localhost:7512/" -> { - val responseHeaders = headersOf("Content-Type" to listOf("application/json")) - respond("{}", headers = responseHeaders) + @KtorExperimentalAPI + @Before + fun setup() { + socket = MockedSocket("localhost") + socket?.mockedClient = HttpClient(MockEngine) { + install(JsonFeature) { + serializer = GsonSerializer() + acceptContentTypes += ContentType("application", "json") + } + engine { + addHandler { request -> + when (request.url.toString()) { + "ws://localhost:7512/" -> { + val responseHeaders = headersOf("Content-Type" to listOf("application/json")) + respond("{}", headers = responseHeaders) + } + else -> error("Unhandled ${request.url.fullPath}") + } + } } - else -> error("Unhandled ${request.url.fullPath}") - } } - } } - } - - @Test - fun constructorNotConnected() { - assertEquals(ProtocolState.CLOSE, socket?.state) - } - @KtorExperimentalAPI - @Test - fun connectTest() { - assertEquals(ProtocolState.CLOSE, socket?.state) - socket?.connect() - assertNotEquals(ProtocolState.CLOSE, socket?.state) - socket?.disconnect() - socket = null - } + @Test + fun constructorNotConnected() { + assertEquals(ProtocolState.CLOSE, socket?.state) + } - @KtorExperimentalAPI - @Test - fun sendTest() { - val query = ConcurrentHashMap().apply { - put("controller", "server") - put("action", "now") + @KtorExperimentalAPI + @Test + fun connectTest() { + assertEquals(ProtocolState.CLOSE, socket?.state) + socket?.connect() + assertNotEquals(ProtocolState.CLOSE, socket?.state) + socket?.disconnect() + socket = null } - socket?.connect() - socket?.send(query) - socket?.disconnect() - socket = null - } + @KtorExperimentalAPI + @Test + fun sendTest() { + val query = ConcurrentHashMap().apply { + put("controller", "server") + put("action", "now") + } + socket?.connect() + socket?.send(query) + socket?.disconnect() + socket = null + } } From e2d9e1c24d1396ef95a0a94454fa99f26fe677a1 Mon Sep 17 00:00:00 2001 From: Alexandre Bouthinon Date: Thu, 21 Jan 2021 13:41:59 +0100 Subject: [PATCH 05/11] Import UUID from java.util --- src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt b/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt index ebe344ac..9cff9549 100644 --- a/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt +++ b/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt @@ -17,6 +17,7 @@ import io.kuzzle.sdk.protocol.AbstractProtocol import io.kuzzle.sdk.protocol.ProtocolState import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap +import java.util.UUID import kotlin.collections.HashMap class Kuzzle { From a6354d3538df9b014d13e563d36059bb9de91b7f Mon Sep 17 00:00:00 2001 From: Alexandre Bouthinon Date: Thu, 21 Jan 2021 13:45:39 +0100 Subject: [PATCH 06/11] Fix org.junit.Assert import --- src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt b/src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt index b66cde22..f1a25913 100644 --- a/src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt +++ b/src/test/kotlin/io/kuzzle/sdk/protocolTest/WebSocketTests.kt @@ -11,6 +11,8 @@ import io.ktor.http.headersOf import io.ktor.util.KtorExperimentalAPI import io.kuzzle.sdk.protocol.ProtocolState import io.kuzzle.sdk.protocol.WebSocket +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals import org.junit.Before import org.junit.Test import java.util.concurrent.ConcurrentHashMap From 6e4dfaf8c7b98c36d187ac8985a104de234608bb Mon Sep 17 00:00:00 2001 From: Alexandre Bouthinon Date: Thu, 21 Jan 2021 13:48:10 +0100 Subject: [PATCH 07/11] Run klint auto fix --- src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt b/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt index 9cff9549..2e65dd4e 100644 --- a/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt +++ b/src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt @@ -15,9 +15,9 @@ import io.kuzzle.sdk.coreClasses.maps.KuzzleMap import io.kuzzle.sdk.coreClasses.responses.Response import io.kuzzle.sdk.protocol.AbstractProtocol import io.kuzzle.sdk.protocol.ProtocolState +import java.util.UUID import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap -import java.util.UUID import kotlin.collections.HashMap class Kuzzle { From 43d836063cca99ee6dbac516b671176a2d9b5a80 Mon Sep 17 00:00:00 2001 From: Alexandre Bouthinon Date: Fri, 22 Jan 2021 00:12:52 +0100 Subject: [PATCH 08/11] Run ktlint auto fix on Kotlin snippets --- .../snippets/check-rights-kotlin.kt | 14 +-- .../snippets/check-token-kotlin.kt | 13 ++- .../auth/login/snippets/login-kotlin.kt | 11 ++- .../snippets/delete-by-query-kotlin.kt | 16 +++- .../snippets/import-data-kotlin.kt | 93 +++++++++++-------- .../bulk/m-write/snippets/mwrite-kotlin.kt | 16 ++-- .../bulk/write/snippets/write-kotlin.kt | 15 +-- .../exists/snippets/exists-kotlin.kt | 2 +- .../snippets/get-mapping-kotlin.kt | 4 +- .../snippets/get-specifications-kotlin.kt | 4 +- .../collection/list/snippets/list-kotlin.kt | 4 +- .../snippets/update-specifications-kotlin.kt | 24 ++--- .../validate-specifications-kotlin.kt | 12 +-- .../document/count/snippets/count-kotlin.kt | 17 ++-- .../snippets/create-or-replace-kotlin.kt | 4 +- .../document/create/snippets/create-kotlin.kt | 8 +- .../snippets/delete-by-query-kotlin.kt | 22 +++-- .../document/exists/snippets/exists-kotlin.kt | 6 +- .../snippets/m-create-or-replace-kotlin.kt | 26 ++++-- .../m-create/snippets/m-create-kotlin.kt | 26 ++++-- .../m-delete/snippets/m-delete-kotlin.kt | 6 +- .../document/m-get/snippets/m-get-kotlin.kt | 6 +- .../m-replace/snippets/m-replace-kotlin.kt | 47 +++++----- .../m-update/snippets/m-update-kotlin.kt | 47 +++++----- .../replace/snippets/replace-kotlin.kt | 14 +-- .../document/search/snippets/search-kotlin.kt | 24 ++--- .../snippets/update-by-query-kotlin.kt | 29 +++--- .../document/update/snippets/update-kotlin.kt | 14 +-- .../validate/snippets/validate-kotlin.kt | 16 ++-- .../realtime/count/snippets/count-kotlin.kt | 17 ++-- .../snippets/admin-exists-kotlin.kt | 2 +- .../snippets/get-all-stats-kotlin.kt | 2 +- .../get-config/snippets/get-config-kotlin.kt | 2 +- .../snippets/get-last-stats-kotlin.kt | 2 +- .../get-stats/snippets/get-stats-kotlin.kt | 6 +- .../server/info/snippets/info-kotlin.kt | 2 +- .../server/now/snippets/now-kotlin.kt | 2 +- .../kuzzle/query/snippets/query-kotlin.kt | 23 +++-- .../kotlin/snippets/document-kotlin.kt | 64 +++++++------ .../kotlin/snippets/firstconnection-kotlin.kt | 62 ++++++------- .../kotlin/snippets/realtime-kotlin.kt | 93 +++++++++---------- 41 files changed, 438 insertions(+), 379 deletions(-) diff --git a/doc/1/controllers/auth/check-rights/snippets/check-rights-kotlin.kt b/doc/1/controllers/auth/check-rights/snippets/check-rights-kotlin.kt index abd112be..9570406b 100644 --- a/doc/1/controllers/auth/check-rights/snippets/check-rights-kotlin.kt +++ b/doc/1/controllers/auth/check-rights/snippets/check-rights-kotlin.kt @@ -1,13 +1,13 @@ val body = ConcurrentHashMap().apply { - put("name", "Melis") + put("name", "Melis") } val requestPayload = ConcurrentHashMap().apply { - put("controller", "document") - put("action", "create") - put("index", "nyc-open-data") - put("collection", "yellow-taxi") - put("body", body) + put("controller", "document") + put("action", "create") + put("index", "nyc-open-data") + put("collection", "yellow-taxi") + put("body", body) } -val result = kuzzle.authController.checkRights(requestPayload).get() \ No newline at end of file +val result = kuzzle.authController.checkRights(requestPayload).get() diff --git a/doc/1/controllers/auth/check-token/snippets/check-token-kotlin.kt b/doc/1/controllers/auth/check-token/snippets/check-token-kotlin.kt index 84fa15b4..9d4e8c22 100644 --- a/doc/1/controllers/auth/check-token/snippets/check-token-kotlin.kt +++ b/doc/1/controllers/auth/check-token/snippets/check-token-kotlin.kt @@ -1,7 +1,10 @@ -val response = kuzzle.authController.login("local", ConcurrentHashMap().apply { - put("username", "foo") - put("password", "bar") -}).get() +val response = kuzzle.authController.login( + "local", + ConcurrentHashMap().apply { + put("username", "foo") + put("password", "bar") + } +).get() val responseToken: ConcurrentHashMap = - kuzzle.authController.checkToken(response["jwt"].toString()).get() \ No newline at end of file + kuzzle.authController.checkToken(response["jwt"].toString()).get() diff --git a/doc/1/controllers/auth/login/snippets/login-kotlin.kt b/doc/1/controllers/auth/login/snippets/login-kotlin.kt index c825d6b4..4dee9687 100644 --- a/doc/1/controllers/auth/login/snippets/login-kotlin.kt +++ b/doc/1/controllers/auth/login/snippets/login-kotlin.kt @@ -1,5 +1,8 @@ val result: ConcurrentHashMap = - kuzzle.authController.login("local", ConcurrentHashMap().apply { - put("username", "foo") - put("password", "bar") - }).get() \ No newline at end of file + kuzzle.authController.login( + "local", + ConcurrentHashMap().apply { + put("username", "foo") + put("password", "bar") + } + ).get() diff --git a/doc/1/controllers/bulk/delete-by-query/snippets/delete-by-query-kotlin.kt b/doc/1/controllers/bulk/delete-by-query/snippets/delete-by-query-kotlin.kt index 4e6cfabb..bbb42a66 100644 --- a/doc/1/controllers/bulk/delete-by-query/snippets/delete-by-query-kotlin.kt +++ b/doc/1/controllers/bulk/delete-by-query/snippets/delete-by-query-kotlin.kt @@ -1,9 +1,15 @@ val searchQuery: ConcurrentHashMap = ConcurrentHashMap().apply { - put("query", ConcurrentHashMap().apply { - put("term", ConcurrentHashMap().apply { - put("capacity", 7) - }) - }) + put( + "query", + ConcurrentHashMap().apply { + put( + "term", + ConcurrentHashMap().apply { + put("capacity", 7) + } + ) + } + ) } val result: Int = kuzzle.bulkController.deleteByQuery("nyc-open-data", "yellow-taxi", searchQuery).get() diff --git a/doc/1/controllers/bulk/import-data/snippets/import-data-kotlin.kt b/doc/1/controllers/bulk/import-data/snippets/import-data-kotlin.kt index 0707aed3..9a77272f 100644 --- a/doc/1/controllers/bulk/import-data/snippets/import-data-kotlin.kt +++ b/doc/1/controllers/bulk/import-data/snippets/import-data-kotlin.kt @@ -1,42 +1,57 @@ val bulkData: ArrayList> = ArrayList>().apply { - add(ConcurrentHashMap().apply { - put("index", ConcurrentHashMap()); - }); - add(ConcurrentHashMap().apply { - put("a", "document"); - put("with", "any"); - put("number", "of fields"); - }); - add(ConcurrentHashMap().apply { - put("create", - ConcurrentHashMap().apply { - put("_id", "uniq-id-1"); - } - ); - }); - add(ConcurrentHashMap().apply { - put("another", "document"); - }); - add(ConcurrentHashMap().apply { - put("create", - ConcurrentHashMap().apply { - put("_id", "uniq-id-2"); - } - ); - }); - add(ConcurrentHashMap().apply { - put("and", - ConcurrentHashMap().apply { - put("another", "one"); - } - ); - }); -}; + add( + ConcurrentHashMap().apply { + put("index", ConcurrentHashMap()) + } + ) + add( + ConcurrentHashMap().apply { + put("a", "document") + put("with", "any") + put("number", "of fields") + } + ) + add( + ConcurrentHashMap().apply { + put( + "create", + ConcurrentHashMap().apply { + put("_id", "uniq-id-1") + } + ) + } + ) + add( + ConcurrentHashMap().apply { + put("another", "document") + } + ) + add( + ConcurrentHashMap().apply { + put( + "create", + ConcurrentHashMap().apply { + put("_id", "uniq-id-2") + } + ) + } + ) + add( + ConcurrentHashMap().apply { + put( + "and", + ConcurrentHashMap().apply { + put("another", "one") + } + ) + } + ) +} val result: ConcurrentHashMap = - kuzzle.bulkController.importData( - "nyc-open-data", - "yellow-taxi", - bulkData - ) - .get() \ No newline at end of file + kuzzle.bulkController.importData( + "nyc-open-data", + "yellow-taxi", + bulkData + ) + .get() diff --git a/doc/1/controllers/bulk/m-write/snippets/mwrite-kotlin.kt b/doc/1/controllers/bulk/m-write/snippets/mwrite-kotlin.kt index 65801dfe..4174363a 100644 --- a/doc/1/controllers/bulk/m-write/snippets/mwrite-kotlin.kt +++ b/doc/1/controllers/bulk/m-write/snippets/mwrite-kotlin.kt @@ -1,9 +1,11 @@ val documents: ArrayList> = ArrayList>().apply { - add(ConcurrentHashMap().apply { - put("_id", "foo") - put("body", ConcurrentHashMap()) - }) -}; + add( + ConcurrentHashMap().apply { + put("_id", "foo") + put("body", ConcurrentHashMap()) + } + ) +} -val result: ConcurrentHashMap = -kuzzle.bulkController.mWrite("nyc-open-data", "yellow-taxi", documents).get(); \ No newline at end of file +val result: ConcurrentHashMap = + kuzzle.bulkController.mWrite("nyc-open-data", "yellow-taxi", documents).get() diff --git a/doc/1/controllers/bulk/write/snippets/write-kotlin.kt b/doc/1/controllers/bulk/write/snippets/write-kotlin.kt index 7cef1c2e..7a3aafdb 100644 --- a/doc/1/controllers/bulk/write/snippets/write-kotlin.kt +++ b/doc/1/controllers/bulk/write/snippets/write-kotlin.kt @@ -1,9 +1,12 @@ val content: ConcurrentHashMap = ConcurrentHashMap().apply { - put("_kuzzle_info", ConcurrentHashMap().apply { - put("author", "") - put("createdAd", "1481816934209") - }); + put( + "_kuzzle_info", + ConcurrentHashMap().apply { + put("author", "") + put("createdAd", "1481816934209") + } + ) } -val result: ConcurrentHashMap = -kuzzle.bulkController.write("nyc-open-data", "yellow-taxi", content).get(); \ No newline at end of file +val result: ConcurrentHashMap = + kuzzle.bulkController.write("nyc-open-data", "yellow-taxi", content).get() diff --git a/doc/1/controllers/collection/exists/snippets/exists-kotlin.kt b/doc/1/controllers/collection/exists/snippets/exists-kotlin.kt index 76bd38e1..89ba15b9 100644 --- a/doc/1/controllers/collection/exists/snippets/exists-kotlin.kt +++ b/doc/1/controllers/collection/exists/snippets/exists-kotlin.kt @@ -1,4 +1,4 @@ val result = kuzzle .collectionController .exists("nyc-open-data", "yellow-taxi") - .get(); + .get() diff --git a/doc/1/controllers/collection/get-mapping/snippets/get-mapping-kotlin.kt b/doc/1/controllers/collection/get-mapping/snippets/get-mapping-kotlin.kt index c8c36c5d..6cf8be7d 100644 --- a/doc/1/controllers/collection/get-mapping/snippets/get-mapping-kotlin.kt +++ b/doc/1/controllers/collection/get-mapping/snippets/get-mapping-kotlin.kt @@ -1,7 +1,7 @@ val result = kuzzle .collectionController .getMapping("nyc-open-data", "yellow-taxi") - .get(); + .get() /* { @@ -16,4 +16,4 @@ val result = kuzzle } } } -*/ \ No newline at end of file +*/ diff --git a/doc/1/controllers/collection/get-specifications/snippets/get-specifications-kotlin.kt b/doc/1/controllers/collection/get-specifications/snippets/get-specifications-kotlin.kt index a4776800..5b0ce36e 100644 --- a/doc/1/controllers/collection/get-specifications/snippets/get-specifications-kotlin.kt +++ b/doc/1/controllers/collection/get-specifications/snippets/get-specifications-kotlin.kt @@ -1,7 +1,7 @@ val result = kuzzle .collectionController .getSpecifications("nyc-open-data", "yellow-taxi") - .get(); + .get() /* { @@ -18,4 +18,4 @@ val result = kuzzle strict=true } } -*/ \ No newline at end of file +*/ diff --git a/doc/1/controllers/collection/list/snippets/list-kotlin.kt b/doc/1/controllers/collection/list/snippets/list-kotlin.kt index 6b4f60ac..b1c46524 100644 --- a/doc/1/controllers/collection/list/snippets/list-kotlin.kt +++ b/doc/1/controllers/collection/list/snippets/list-kotlin.kt @@ -1,7 +1,7 @@ val result = kuzzle .collectionController .list("nyc-open-data") - .get(); + .get() /* { @@ -19,4 +19,4 @@ val result = kuzzle from=0, type=all } - */ \ No newline at end of file + */ diff --git a/doc/1/controllers/collection/update-specifications/snippets/update-specifications-kotlin.kt b/doc/1/controllers/collection/update-specifications/snippets/update-specifications-kotlin.kt index d86cd43a..59fcef79 100644 --- a/doc/1/controllers/collection/update-specifications/snippets/update-specifications-kotlin.kt +++ b/doc/1/controllers/collection/update-specifications/snippets/update-specifications-kotlin.kt @@ -1,22 +1,22 @@ val license: ConcurrentHashMap = -ConcurrentHashMap().apply { - put("mandatory", true); - put("type", "string"); -}; + ConcurrentHashMap().apply { + put("mandatory", true) + put("type", "string") + } val fields: ConcurrentHashMap = -ConcurrentHashMap().apply { - put("license", license); -}; + ConcurrentHashMap().apply { + put("license", license) + } val specifications: ConcurrentHashMap = -ConcurrentHashMap().apply{ - put("strict", false); - put("fields", fields); -}; + ConcurrentHashMap().apply { + put("strict", false) + put("fields", fields) + } val result: ConcurrentHashMap = kuzzle .collectionController .updateSpecifications("nyc-open-data", "yellow-taxi", specifications) - .get(); + .get() /* { diff --git a/doc/1/controllers/collection/validate-specifications/snippets/validate-specifications-kotlin.kt b/doc/1/controllers/collection/validate-specifications/snippets/validate-specifications-kotlin.kt index 85e01caa..38aeed3a 100644 --- a/doc/1/controllers/collection/validate-specifications/snippets/validate-specifications-kotlin.kt +++ b/doc/1/controllers/collection/validate-specifications/snippets/validate-specifications-kotlin.kt @@ -1,16 +1,16 @@ val license: ConcurrentHashMap = ConcurrentHashMap().apply { - put("type", "symbol") - put("mandatory", true) + put("type", "symbol") + put("mandatory", true) } val fields: ConcurrentHashMap = ConcurrentHashMap().apply { - put("license", license) + put("license", license) } val specifications: ConcurrentHashMap = ConcurrentHashMap().apply { - put("strict", false) - put("fields", fields) + put("strict", false) + put("fields", fields) } val result = kuzzle .collectionController .validateSpecifications("nyc-open-data", "yellow-taxi", specifications) - .get(); + .get() diff --git a/doc/1/controllers/document/count/snippets/count-kotlin.kt b/doc/1/controllers/document/count/snippets/count-kotlin.kt index 141f6fff..78e1c66a 100644 --- a/doc/1/controllers/document/count/snippets/count-kotlin.kt +++ b/doc/1/controllers/document/count/snippets/count-kotlin.kt @@ -1,11 +1,14 @@ -val searchQuery : ConcurrentHashMap = +val searchQuery: ConcurrentHashMap = ConcurrentHashMap().apply { - put("match", ConcurrentHashMap().apply { - put("Hello", "Clarisse") - }) + put( + "match", + ConcurrentHashMap().apply { + put("Hello", "Clarisse") + } + ) } val result: Int = kuzzle - .documentController - .count("nyc-open-data", "yellow-taxi", searchQuery) - .get(); \ No newline at end of file + .documentController + .count("nyc-open-data", "yellow-taxi", searchQuery) + .get() diff --git a/doc/1/controllers/document/create-or-replace/snippets/create-or-replace-kotlin.kt b/doc/1/controllers/document/create-or-replace/snippets/create-or-replace-kotlin.kt index 9d12a6d0..a56333d4 100644 --- a/doc/1/controllers/document/create-or-replace/snippets/create-or-replace-kotlin.kt +++ b/doc/1/controllers/document/create-or-replace/snippets/create-or-replace-kotlin.kt @@ -1,9 +1,9 @@ val document: ConcurrentHashMap = ConcurrentHashMap().apply { - put("firstname", "John") + put("firstname", "John") } val result: ConcurrentHashMap = kuzzle .documentController .createOrReplace("nyc-open-data", "yellow-taxi", "some-id", document) - .get(); \ No newline at end of file + .get() diff --git a/doc/1/controllers/document/create/snippets/create-kotlin.kt b/doc/1/controllers/document/create/snippets/create-kotlin.kt index 7581cd38..5177359d 100644 --- a/doc/1/controllers/document/create/snippets/create-kotlin.kt +++ b/doc/1/controllers/document/create/snippets/create-kotlin.kt @@ -1,9 +1,9 @@ val document: ConcurrentHashMap = ConcurrentHashMap().apply { - put("firstname", "John") + put("firstname", "John") } val result: ConcurrentHashMap = kuzzle - .documentController - .create("nyc-open-data", "yellow-taxi", document) - .get(); \ No newline at end of file + .documentController + .create("nyc-open-data", "yellow-taxi", document) + .get() diff --git a/doc/1/controllers/document/delete-by-query/snippets/delete-by-query-kotlin.kt b/doc/1/controllers/document/delete-by-query/snippets/delete-by-query-kotlin.kt index b5c68df8..50f6a2d4 100644 --- a/doc/1/controllers/document/delete-by-query/snippets/delete-by-query-kotlin.kt +++ b/doc/1/controllers/document/delete-by-query/snippets/delete-by-query-kotlin.kt @@ -1,12 +1,18 @@ val searchQuery: ConcurrentHashMap = ConcurrentHashMap().apply { - put("query", ConcurrentHashMap().apply { - put("match", ConcurrentHashMap().apply { - put("capacity", 4) - }) - }) + put( + "query", + ConcurrentHashMap().apply { + put( + "match", + ConcurrentHashMap().apply { + put("capacity", 4) + } + ) + } + ) } val result: ArrayList = kuzzle - .documentController - .deleteByQuery("nyc-open-data", "yellow-taxi", searchQuery) - .get() + .documentController + .deleteByQuery("nyc-open-data", "yellow-taxi", searchQuery) + .get() diff --git a/doc/1/controllers/document/exists/snippets/exists-kotlin.kt b/doc/1/controllers/document/exists/snippets/exists-kotlin.kt index 4a5ffbc8..386afd6a 100644 --- a/doc/1/controllers/document/exists/snippets/exists-kotlin.kt +++ b/doc/1/controllers/document/exists/snippets/exists-kotlin.kt @@ -1,4 +1,4 @@ val result: Boolean = kuzzle - .documentController - .exists("nyc-open-data", "yellow-taxi", "some-id") - .get() + .documentController + .exists("nyc-open-data", "yellow-taxi", "some-id") + .get() diff --git a/doc/1/controllers/document/m-create-or-replace/snippets/m-create-or-replace-kotlin.kt b/doc/1/controllers/document/m-create-or-replace/snippets/m-create-or-replace-kotlin.kt index fa1f73fa..de72fc73 100644 --- a/doc/1/controllers/document/m-create-or-replace/snippets/m-create-or-replace-kotlin.kt +++ b/doc/1/controllers/document/m-create-or-replace/snippets/m-create-or-replace-kotlin.kt @@ -1,23 +1,29 @@ val document1: ConcurrentHashMap = ConcurrentHashMap().apply { - put("_id", "some-id") - put("body", ConcurrentHashMap().apply { - put("Agent", "Smith") - }) + put("_id", "some-id") + put( + "body", + ConcurrentHashMap().apply { + put("Agent", "Smith") + } + ) } val document2: ConcurrentHashMap = ConcurrentHashMap().apply { - put("_id", "some-id2") - put("body", ConcurrentHashMap().apply { - put("Gordon", "Freeman") - }) + put("_id", "some-id2") + put( + "body", + ConcurrentHashMap().apply { + put("Gordon", "Freeman") + } + ) } val documents: ArrayList> = ArrayList>().apply { - add(document1) - add(document2) + add(document1) + add(document2) } val result: ConcurrentHashMap> = diff --git a/doc/1/controllers/document/m-create/snippets/m-create-kotlin.kt b/doc/1/controllers/document/m-create/snippets/m-create-kotlin.kt index fa1f73fa..de72fc73 100644 --- a/doc/1/controllers/document/m-create/snippets/m-create-kotlin.kt +++ b/doc/1/controllers/document/m-create/snippets/m-create-kotlin.kt @@ -1,23 +1,29 @@ val document1: ConcurrentHashMap = ConcurrentHashMap().apply { - put("_id", "some-id") - put("body", ConcurrentHashMap().apply { - put("Agent", "Smith") - }) + put("_id", "some-id") + put( + "body", + ConcurrentHashMap().apply { + put("Agent", "Smith") + } + ) } val document2: ConcurrentHashMap = ConcurrentHashMap().apply { - put("_id", "some-id2") - put("body", ConcurrentHashMap().apply { - put("Gordon", "Freeman") - }) + put("_id", "some-id2") + put( + "body", + ConcurrentHashMap().apply { + put("Gordon", "Freeman") + } + ) } val documents: ArrayList> = ArrayList>().apply { - add(document1) - add(document2) + add(document1) + add(document2) } val result: ConcurrentHashMap> = diff --git a/doc/1/controllers/document/m-delete/snippets/m-delete-kotlin.kt b/doc/1/controllers/document/m-delete/snippets/m-delete-kotlin.kt index 08502caa..55516d0f 100644 --- a/doc/1/controllers/document/m-delete/snippets/m-delete-kotlin.kt +++ b/doc/1/controllers/document/m-delete/snippets/m-delete-kotlin.kt @@ -5,6 +5,6 @@ val ids: ArrayList = ArrayList().apply { val result: ConcurrentHashMap> = kuzzle - .documentController - .mDelete("nyc-open-data", "yellow-taxi", ids) - .get() \ No newline at end of file + .documentController + .mDelete("nyc-open-data", "yellow-taxi", ids) + .get() diff --git a/doc/1/controllers/document/m-get/snippets/m-get-kotlin.kt b/doc/1/controllers/document/m-get/snippets/m-get-kotlin.kt index d98dd7e7..7c3bfb80 100644 --- a/doc/1/controllers/document/m-get/snippets/m-get-kotlin.kt +++ b/doc/1/controllers/document/m-get/snippets/m-get-kotlin.kt @@ -5,6 +5,6 @@ val ids: ArrayList = ArrayList().apply { val result: ConcurrentHashMap> = kuzzle - .documentController - .mGet("nyc-open-data", "yellow-taxi", ids) - .get() + .documentController + .mGet("nyc-open-data", "yellow-taxi", ids) + .get() diff --git a/doc/1/controllers/document/m-replace/snippets/m-replace-kotlin.kt b/doc/1/controllers/document/m-replace/snippets/m-replace-kotlin.kt index a2ebdb9b..7db7980e 100644 --- a/doc/1/controllers/document/m-replace/snippets/m-replace-kotlin.kt +++ b/doc/1/controllers/document/m-replace/snippets/m-replace-kotlin.kt @@ -1,28 +1,33 @@ -val document1: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("_id", "some-id") - put("body", ConcurrentHashMap().apply { - put("name", "Smith") - }) - } +val document1: ConcurrentHashMap = + ConcurrentHashMap().apply { + put("_id", "some-id") + put( + "body", + ConcurrentHashMap().apply { + put("name", "Smith") + } + ) + } -val document2: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("_id", "some-id2") - put("body", ConcurrentHashMap().apply { - put("name", "Freeman") - }) - } +val document2: ConcurrentHashMap = + ConcurrentHashMap().apply { + put("_id", "some-id2") + put( + "body", + ConcurrentHashMap().apply { + put("name", "Freeman") + } + ) + } val documents: ArrayList> = ArrayList>().apply { - add(document1) - add(document2) + add(document1) + add(document2) } - val result: ConcurrentHashMap?> = - kuzzle - .documentController - .mReplace("nyc-open-data", "yellow-taxi", documents) - .get() \ No newline at end of file + kuzzle + .documentController + .mReplace("nyc-open-data", "yellow-taxi", documents) + .get() diff --git a/doc/1/controllers/document/m-update/snippets/m-update-kotlin.kt b/doc/1/controllers/document/m-update/snippets/m-update-kotlin.kt index a2ebdb9b..7db7980e 100644 --- a/doc/1/controllers/document/m-update/snippets/m-update-kotlin.kt +++ b/doc/1/controllers/document/m-update/snippets/m-update-kotlin.kt @@ -1,28 +1,33 @@ -val document1: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("_id", "some-id") - put("body", ConcurrentHashMap().apply { - put("name", "Smith") - }) - } +val document1: ConcurrentHashMap = + ConcurrentHashMap().apply { + put("_id", "some-id") + put( + "body", + ConcurrentHashMap().apply { + put("name", "Smith") + } + ) + } -val document2: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("_id", "some-id2") - put("body", ConcurrentHashMap().apply { - put("name", "Freeman") - }) - } +val document2: ConcurrentHashMap = + ConcurrentHashMap().apply { + put("_id", "some-id2") + put( + "body", + ConcurrentHashMap().apply { + put("name", "Freeman") + } + ) + } val documents: ArrayList> = ArrayList>().apply { - add(document1) - add(document2) + add(document1) + add(document2) } - val result: ConcurrentHashMap?> = - kuzzle - .documentController - .mReplace("nyc-open-data", "yellow-taxi", documents) - .get() \ No newline at end of file + kuzzle + .documentController + .mReplace("nyc-open-data", "yellow-taxi", documents) + .get() diff --git a/doc/1/controllers/document/replace/snippets/replace-kotlin.kt b/doc/1/controllers/document/replace/snippets/replace-kotlin.kt index 6f09f572..0ad8db56 100644 --- a/doc/1/controllers/document/replace/snippets/replace-kotlin.kt +++ b/doc/1/controllers/document/replace/snippets/replace-kotlin.kt @@ -1,10 +1,10 @@ val document: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("firstname", "John") - } + ConcurrentHashMap().apply { + put("firstname", "John") + } val result: ConcurrentHashMap = - kuzzle - .documentController - .replace("nyc-open-data", "yellow-taxi", "some-id", document) - .get() + kuzzle + .documentController + .replace("nyc-open-data", "yellow-taxi", "some-id", document) + .get() diff --git a/doc/1/controllers/document/search/snippets/search-kotlin.kt b/doc/1/controllers/document/search/snippets/search-kotlin.kt index c72f6a89..263738d2 100644 --- a/doc/1/controllers/document/search/snippets/search-kotlin.kt +++ b/doc/1/controllers/document/search/snippets/search-kotlin.kt @@ -1,19 +1,19 @@ val match: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("category", "suv") - } + ConcurrentHashMap().apply { + put("category", "suv") + } val query: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("match", match) - } + ConcurrentHashMap().apply { + put("match", match) + } val searchQuery: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("query", query) - } + ConcurrentHashMap().apply { + put("query", query) + } val results = kuzzle - .documentController - .search("nyc-open-data", "yellow-taxi", searchQuery).get(); + .documentController + .search("nyc-open-data", "yellow-taxi", searchQuery).get() /* { @@ -38,4 +38,4 @@ val results = kuzzle "total"=5, "fetched"=5, "scroll_id"=undefined -*/ \ No newline at end of file +*/ diff --git a/doc/1/controllers/document/update-by-query/snippets/update-by-query-kotlin.kt b/doc/1/controllers/document/update-by-query/snippets/update-by-query-kotlin.kt index 2da4523c..c0534297 100644 --- a/doc/1/controllers/document/update-by-query/snippets/update-by-query-kotlin.kt +++ b/doc/1/controllers/document/update-by-query/snippets/update-by-query-kotlin.kt @@ -1,24 +1,23 @@ val match: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("capacity", 4) - } + ConcurrentHashMap().apply { + put("capacity", 4) + } val searchQuery: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("match", match) - } + ConcurrentHashMap().apply { + put("match", match) + } val changes: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("capacity", 42) - } - + ConcurrentHashMap().apply { + put("capacity", 42) + } val result: ConcurrentHashMap> = - kuzzle - .documentController - .updateByQuery("nyc-open-data", "yellow-taxi", searchQuery, changes) - .get() + kuzzle + .documentController + .updateByQuery("nyc-open-data", "yellow-taxi", searchQuery, changes) + .get() /* { @@ -36,4 +35,4 @@ val result: ConcurrentHashMap> = ], errors=[] } -*/ \ No newline at end of file +*/ diff --git a/doc/1/controllers/document/update/snippets/update-kotlin.kt b/doc/1/controllers/document/update/snippets/update-kotlin.kt index a959c53c..08c51c97 100644 --- a/doc/1/controllers/document/update/snippets/update-kotlin.kt +++ b/doc/1/controllers/document/update/snippets/update-kotlin.kt @@ -1,10 +1,10 @@ val document: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("name", "Johny") - } + ConcurrentHashMap().apply { + put("name", "Johny") + } val result: ConcurrentHashMap = - kuzzle - .documentController - .update("nyc-open-data", "yellow-taxi", "some-id", document) - .get() + kuzzle + .documentController + .update("nyc-open-data", "yellow-taxi", "some-id", document) + .get() diff --git a/doc/1/controllers/document/validate/snippets/validate-kotlin.kt b/doc/1/controllers/document/validate/snippets/validate-kotlin.kt index 4ef6c398..80598711 100644 --- a/doc/1/controllers/document/validate/snippets/validate-kotlin.kt +++ b/doc/1/controllers/document/validate/snippets/validate-kotlin.kt @@ -1,12 +1,10 @@ val document: ConcurrentHashMap = - ConcurrentHashMap().apply { - put("key", "value") - } - + ConcurrentHashMap().apply { + put("key", "value") + } val result: Boolean = - kuzzle - .documentController - .validate("nyc-open-data", "yellow-taxi", document) - .get() - \ No newline at end of file + kuzzle + .documentController + .validate("nyc-open-data", "yellow-taxi", document) + .get() diff --git a/doc/1/controllers/realtime/count/snippets/count-kotlin.kt b/doc/1/controllers/realtime/count/snippets/count-kotlin.kt index 69452580..940abf72 100644 --- a/doc/1/controllers/realtime/count/snippets/count-kotlin.kt +++ b/doc/1/controllers/realtime/count/snippets/count-kotlin.kt @@ -1,16 +1,17 @@ val filters: ConcurrentHashMap = ConcurrentHashMap().apply { - put("exists", "name") + put("exists", "name") } val roomId: String = kuzzle.realtimeController.subscribe( - "nyc-open-data", - "yellow-taxi", - filters) { + "nyc-open-data", + "yellow-taxi", + filters +) { if (it.scope == "in") { - println("Document entered the scope") + println("Document entered the scope") } else { - println("Document left the scope") + println("Document left the scope") } - }.get() +}.get() -val result: Int = kuzzle.realtimeController.count(roomId).get() \ No newline at end of file +val result: Int = kuzzle.realtimeController.count(roomId).get() diff --git a/doc/1/controllers/server/admin-exists/snippets/admin-exists-kotlin.kt b/doc/1/controllers/server/admin-exists/snippets/admin-exists-kotlin.kt index 6e7a6d5e..774d9571 100644 --- a/doc/1/controllers/server/admin-exists/snippets/admin-exists-kotlin.kt +++ b/doc/1/controllers/server/admin-exists/snippets/admin-exists-kotlin.kt @@ -1,2 +1,2 @@ val result: Boolean = - kuzzle.serverController.adminExists().get() \ No newline at end of file + kuzzle.serverController.adminExists().get() diff --git a/doc/1/controllers/server/get-all-stats/snippets/get-all-stats-kotlin.kt b/doc/1/controllers/server/get-all-stats/snippets/get-all-stats-kotlin.kt index 89096976..e52921fb 100644 --- a/doc/1/controllers/server/get-all-stats/snippets/get-all-stats-kotlin.kt +++ b/doc/1/controllers/server/get-all-stats/snippets/get-all-stats-kotlin.kt @@ -1,4 +1,4 @@ val result: ConcurrentHashMap = kuzzle .serverController .getAllStats() - .get() \ No newline at end of file + .get() diff --git a/doc/1/controllers/server/get-config/snippets/get-config-kotlin.kt b/doc/1/controllers/server/get-config/snippets/get-config-kotlin.kt index 5000aa6f..a24620e9 100644 --- a/doc/1/controllers/server/get-config/snippets/get-config-kotlin.kt +++ b/doc/1/controllers/server/get-config/snippets/get-config-kotlin.kt @@ -1,4 +1,4 @@ val result: ConcurrentHashMap = kuzzle .serverController .getConfig() - .get() \ No newline at end of file + .get() diff --git a/doc/1/controllers/server/get-last-stats/snippets/get-last-stats-kotlin.kt b/doc/1/controllers/server/get-last-stats/snippets/get-last-stats-kotlin.kt index be0a5ec3..cfb7e160 100644 --- a/doc/1/controllers/server/get-last-stats/snippets/get-last-stats-kotlin.kt +++ b/doc/1/controllers/server/get-last-stats/snippets/get-last-stats-kotlin.kt @@ -1,4 +1,4 @@ val result: ConcurrentHashMap = kuzzle .serverController .getLastStats() - .get() \ No newline at end of file + .get() diff --git a/doc/1/controllers/server/get-stats/snippets/get-stats-kotlin.kt b/doc/1/controllers/server/get-stats/snippets/get-stats-kotlin.kt index d1f60521..54150e7b 100644 --- a/doc/1/controllers/server/get-stats/snippets/get-stats-kotlin.kt +++ b/doc/1/controllers/server/get-stats/snippets/get-stats-kotlin.kt @@ -1,7 +1,7 @@ -val startTime = Date(1234567890000); -val stopTime = Date(1541426610000); +val startTime = Date(1234567890000) +val stopTime = Date(1541426610000) val result: ConcurrentHashMap = kuzzle .serverController .getStats(startTime, stopTime) - .get() \ No newline at end of file + .get() diff --git a/doc/1/controllers/server/info/snippets/info-kotlin.kt b/doc/1/controllers/server/info/snippets/info-kotlin.kt index 0c040467..1afaf37d 100644 --- a/doc/1/controllers/server/info/snippets/info-kotlin.kt +++ b/doc/1/controllers/server/info/snippets/info-kotlin.kt @@ -1,4 +1,4 @@ val result: ConcurrentHashMap = kuzzle .serverController .info() - .get() \ No newline at end of file + .get() diff --git a/doc/1/controllers/server/now/snippets/now-kotlin.kt b/doc/1/controllers/server/now/snippets/now-kotlin.kt index e38e5f8b..6f9603bf 100644 --- a/doc/1/controllers/server/now/snippets/now-kotlin.kt +++ b/doc/1/controllers/server/now/snippets/now-kotlin.kt @@ -1,4 +1,4 @@ val result: Date = kuzzle .serverController .now() - .get() \ No newline at end of file + .get() diff --git a/doc/1/core-classes/kuzzle/query/snippets/query-kotlin.kt b/doc/1/core-classes/kuzzle/query/snippets/query-kotlin.kt index 83be6d8e..57593292 100644 --- a/doc/1/core-classes/kuzzle/query/snippets/query-kotlin.kt +++ b/doc/1/core-classes/kuzzle/query/snippets/query-kotlin.kt @@ -1,14 +1,17 @@ val query: ConcurrentHashMap = ConcurrentHashMap().apply { - put("controller", "document") - put("action", "create") - put("index", "nyc-open-data") - put("collection", "yellow-taxi") - put("_id", "my-custom-document-id") - put("refresh", "wait_for") - put("body", ConcurrentHashMap().apply { - put("trip_distance", 4.23) - put("passenger_count", 2) - }) + put("controller", "document") + put("action", "create") + put("index", "nyc-open-data") + put("collection", "yellow-taxi") + put("_id", "my-custom-document-id") + put("refresh", "wait_for") + put( + "body", + ConcurrentHashMap().apply { + put("trip_distance", 4.23) + put("passenger_count", 2) + } + ) } val res: Response = kuzzle.query(query).get() diff --git a/doc/1/getting-started/kotlin/snippets/document-kotlin.kt b/doc/1/getting-started/kotlin/snippets/document-kotlin.kt index 7b377f27..6532d88e 100644 --- a/doc/1/getting-started/kotlin/snippets/document-kotlin.kt +++ b/doc/1/getting-started/kotlin/snippets/document-kotlin.kt @@ -1,38 +1,36 @@ -import io.kuzzle.sdk.*; -import io.kuzzle.sdk.protocol.WebSocket; - -import java.util.concurrent.ConcurrentHashMap; +import io.kuzzle.sdk.* +import io.kuzzle.sdk.protocol.WebSocket +import java.util.concurrent.ConcurrentHashMap fun main() { - // Creates a WebSocket connection. - // Replace "kuzzle" with - // your Kuzzle host name (e.g. "localhost") - val ws = WebSocket("kuzzle"); - - // Instantiates a Kuzzle client - val kuzzle = Kuzzle(ws).apply { - // Connects to the server. - connect() - } - println("Connected!"); + // Creates a WebSocket connection. + // Replace "kuzzle" with + // your Kuzzle host name (e.g. "localhost") + val ws = WebSocket("kuzzle") + + // Instantiates a Kuzzle client + val kuzzle = Kuzzle(ws).apply { + // Connects to the server. + connect() + } + println("Connected!") - try { - // New document content - val content: ConcurrentHashMap = ConcurrentHashMap().apply { - put("name", "John") - put("birthday", "1995-11-27") - put("license", "B") + try { + // New document content + val content: ConcurrentHashMap = ConcurrentHashMap().apply { + put("name", "John") + put("birthday", "1995-11-27") + put("license", "B") + } + // Stores the document in the "yellow-taxi" collection. + kuzzle + .documentController + .create("nyc-open-data", "yellow-taxi", content).get() + println("New document added to the yellow-taxi collection!") + } catch (e: Exception) { + e.printStackTrace() + } finally { + // Disconnects the SDK. + kuzzle.disconnect() } - // Stores the document in the "yellow-taxi" collection. - kuzzle - .documentController - .create( "nyc-open-data", "yellow-taxi", content).get(); - println("New document added to the yellow-taxi collection!") - - } catch(e: Exception) { - e.printStackTrace() - } finally { - // Disconnects the SDK. - kuzzle.disconnect() - } } diff --git a/doc/1/getting-started/kotlin/snippets/firstconnection-kotlin.kt b/doc/1/getting-started/kotlin/snippets/firstconnection-kotlin.kt index 8e3fc1af..3e02f6a8 100644 --- a/doc/1/getting-started/kotlin/snippets/firstconnection-kotlin.kt +++ b/doc/1/getting-started/kotlin/snippets/firstconnection-kotlin.kt @@ -1,38 +1,36 @@ -import io.kuzzle.sdk.*; -import io.kuzzle.sdk.protocol.WebSocket; - -import java.util.concurrent.ConcurrentHashMap; +import io.kuzzle.sdk.* +import io.kuzzle.sdk.protocol.WebSocket fun main() { - // Creates a WebSocket connection. - // Replace "kuzzle" with - // your Kuzzle hostname like "localhost" - val ws = WebSocket("kuzzle"); + // Creates a WebSocket connection. + // Replace "kuzzle" with + // your Kuzzle hostname like "localhost" + val ws = WebSocket("kuzzle") - // Instantiates a Kuzzle client - val kuzzle = Kuzzle(ws).apply { - // Connects to the server. - connect() - }; - println("Connected!") + // Instantiates a Kuzzle client + val kuzzle = Kuzzle(ws).apply { + // Connects to the server. + connect() + } + println("Connected!") - try { - // Freshly installed Kuzzle servers are empty: we need to create - // a new index. - kuzzle - .indexController - .create("nyc-open-data").get(); - println("Index nyc-open-data created!") + try { + // Freshly installed Kuzzle servers are empty: we need to create + // a new index. + kuzzle + .indexController + .create("nyc-open-data").get() + println("Index nyc-open-data created!") - // Creates a collection - kuzzle - .collectionController - .create("nyc-open-data", "yellow-taxi").get(); - println("Collection yellow-taxi created!") - } catch(e: Exception){ - e.printStackTrace() - } finally { - // Disconnects the SDK - kuzzle.disconnect() - } + // Creates a collection + kuzzle + .collectionController + .create("nyc-open-data", "yellow-taxi").get() + println("Collection yellow-taxi created!") + } catch (e: Exception) { + e.printStackTrace() + } finally { + // Disconnects the SDK + kuzzle.disconnect() + } } diff --git a/doc/1/getting-started/kotlin/snippets/realtime-kotlin.kt b/doc/1/getting-started/kotlin/snippets/realtime-kotlin.kt index 5484cce4..039dbc57 100644 --- a/doc/1/getting-started/kotlin/snippets/realtime-kotlin.kt +++ b/doc/1/getting-started/kotlin/snippets/realtime-kotlin.kt @@ -1,36 +1,35 @@ -import io.kuzzle.sdk.*; -import io.kuzzle.sdk.protocol.WebSocket; - -import java.util.concurrent.ConcurrentHashMap; +import io.kuzzle.sdk.* +import io.kuzzle.sdk.protocol.WebSocket +import java.util.concurrent.ConcurrentHashMap fun main() { - // Creates a WebSocket connection. - // Replace "kuzzle" with - // your Kuzzle hostname like "localhost" - val ws = WebSocket("kuzzle"); - - // Instantiates a Kuzzle client - val kuzzle = Kuzzle(ws).apply { - // Connects to the server. - connect() - }; - println("Connected!") + // Creates a WebSocket connection. + // Replace "kuzzle" with + // your Kuzzle hostname like "localhost" + val ws = WebSocket("kuzzle") - try { - // Subscribes to notifications for drivers having a "B" driver license. - val equals: ConcurrentHashMap = ConcurrentHashMap().apply { - put("license", "B") - } - val filters: ConcurrentHashMap = ConcurrentHashMap().apply { - put("equals", equals) + // Instantiates a Kuzzle client + val kuzzle = Kuzzle(ws).apply { + // Connects to the server. + connect() } + println("Connected!") + + try { + // Subscribes to notifications for drivers having a "B" driver license. + val equals: ConcurrentHashMap = ConcurrentHashMap().apply { + put("license", "B") + } + val filters: ConcurrentHashMap = ConcurrentHashMap().apply { + put("equals", equals) + } - // Sends the subscription - kuzzle - .realtimeController - .subscribe("nyc-open-data", "yellow-taxi", filters) { notification -> - val content: ConcurrentHashMap = notification.result as ConcurrentHashMap - println("New created document notification: " + content) + // Sends the subscription + kuzzle + .realtimeController + .subscribe("nyc-open-data", "yellow-taxi", filters) { notification -> + val content: ConcurrentHashMap = notification.result as ConcurrentHashMap + println("New created document notification: " + content) /* { _source={ @@ -45,25 +44,25 @@ fun main() { _version=1 } */ - }.get(); - println("Successfully subscribed!") + }.get() + println("Successfully subscribed!") - // Writes a new document. This triggers a notification - // sent to our subscription. - val content: ConcurrentHashMap = ConcurrentHashMap().apply { - put("name", "John") - put("birthday", "1995-11-27") - put("license", "B") - } + // Writes a new document. This triggers a notification + // sent to our subscription. + val content: ConcurrentHashMap = ConcurrentHashMap().apply { + put("name", "John") + put("birthday", "1995-11-27") + put("license", "B") + } - kuzzle - .documentController - .create("nyc-open-data", "yellow-taxi", content).get(); - println("New document added to the yellow-taxi collection!") - } catch (e: Exception) { - e.printStackTrace() - } finally { - // Disconnects the SDK. - kuzzle.disconnect() - } + kuzzle + .documentController + .create("nyc-open-data", "yellow-taxi", content).get() + println("New document added to the yellow-taxi collection!") + } catch (e: Exception) { + e.printStackTrace() + } finally { + // Disconnects the SDK. + kuzzle.disconnect() + } } From 47e3dc3336b6358cd3e8cef28a5f7f9a4fa16941 Mon Sep 17 00:00:00 2001 From: Alexandre Bouthinon Date: Fri, 22 Jan 2021 00:21:22 +0100 Subject: [PATCH 09/11] Add Lint job and format workflows --- .github/actions/lint/action.yml | 13 +++++ .github/workflows/pull_request.workflow.yml | 22 ++++++-- .github/workflows/push_dev.workflow.yml | 59 ++++++++++++++++----- .github/workflows/push_master.workflow.yml | 53 +++++++++++++++--- 4 files changed, 123 insertions(+), 24 deletions(-) create mode 100644 .github/actions/lint/action.yml diff --git a/.github/actions/lint/action.yml b/.github/actions/lint/action.yml new file mode 100644 index 00000000..5fb00b5a --- /dev/null +++ b/.github/actions/lint/action.yml @@ -0,0 +1,13 @@ +name: Lint +description: Run KTLint +runs: + using: "composite" + steps: + - name: Get ktlint + run: | + curl -sSLO https://github.com/pinterest/ktlint/releases/download/0.40.0/ktlint + chmod a+x ktlint + shell: bash + - name: Run ktlint + run: ./ktlint "src/**/*.kt" + shell: bash diff --git a/.github/workflows/pull_request.workflow.yml b/.github/workflows/pull_request.workflow.yml index 53c6ef85..3c44cacd 100644 --- a/.github/workflows/pull_request.workflow.yml +++ b/.github/workflows/pull_request.workflow.yml @@ -3,8 +3,20 @@ name: Pull request checks on: [pull_request] jobs: + lint: + name: Lint + runs-on: ubuntu-18.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: "8" + architecture: x64 + - uses: ./.github/actions/lint + unit-tests: - name: unit-tests + name: Unit Tests runs-on: ubuntu-18.04 timeout-minutes: 30 steps: @@ -15,8 +27,8 @@ jobs: architecture: x64 - uses: ./.github/actions/unit-tests - snippets-tests: - name: Snippets Tests + documentation-snippets-tests: + name: Documentation - Snippets Tests runs-on: ubuntu-18.04 timeout-minutes: 30 steps: @@ -37,8 +49,8 @@ jobs: node-version: "12" - uses: ./.github/actions/snippets-tests - dead-links: - name: Dead links + documentation-dead-links: + name: Documentation - Dead links check runs-on: ubuntu-18.04 timeout-minutes: 30 steps: diff --git a/.github/workflows/push_dev.workflow.yml b/.github/workflows/push_dev.workflow.yml index faf18f3d..bb0f0de0 100644 --- a/.github/workflows/push_dev.workflow.yml +++ b/.github/workflows/push_dev.workflow.yml @@ -6,20 +6,32 @@ on: - 1-dev jobs: + lint: + name: Lint + runs-on: ubuntu-18.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: "8" + architecture: x64 + - uses: ./.github/actions/lint + unit-tests: - name: unit-tests + name: Unit Tests runs-on: ubuntu-18.04 timeout-minutes: 30 steps: - - uses: actions/checkout@v2 - - uses: actions/setup-java@v1 - with: - java-version: '8.0.0' - architecture: x64 - - uses: ./.github/actions/unit-tests + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: "8" + architecture: x64 + - uses: ./.github/actions/unit-tests - snippets-tests: - name: Snippets Tests + documentation-snippets-tests: + name: Documentation - Snippets Tests runs-on: ubuntu-18.04 timeout-minutes: 30 steps: @@ -40,11 +52,34 @@ jobs: node-version: "12" - uses: ./.github/actions/snippets-tests - doc-dev: - name: Deployment Doc Dev + documentation-dead-links: + name: Documentation - Dead links check + runs-on: ubuntu-18.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - uses: actions/setup-node@v1.4.4 + with: + node-version: "12" + - uses: ./.github/actions/dead-links + + + documentation-staging: + name: Documentation - Deploy to staging runs-on: ubuntu-18.04 timeout-minutes: 30 - needs: [unit-tests, snippets-tests] + needs: [lint, unit-tests, documentation-dead-links, documentation-snippets-tests] steps: - uses: actions/checkout@v2 - name: Cache node modules diff --git a/.github/workflows/push_master.workflow.yml b/.github/workflows/push_master.workflow.yml index 7a7b1536..00a60a2c 100644 --- a/.github/workflows/push_master.workflow.yml +++ b/.github/workflows/push_master.workflow.yml @@ -6,8 +6,20 @@ on: - master jobs: + lint: + name: Lint + runs-on: ubuntu-18.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: "8" + architecture: x64 + - uses: ./.github/actions/lint + unit-tests: - name: unit-tests + name: Unit Tests runs-on: ubuntu-18.04 timeout-minutes: 30 steps: @@ -18,8 +30,8 @@ jobs: architecture: x64 - uses: ./.github/actions/unit-tests - snippets-tests: - name: Snippets Tests + documentation-snippets-tests: + name: Documentation - Snippets Tests runs-on: ubuntu-18.04 timeout-minutes: 30 steps: @@ -40,10 +52,34 @@ jobs: node-version: "12" - uses: ./.github/actions/snippets-tests - doc-master: - name: Deployment Doc master + documentation-dead-links: + name: Documentation - Dead links check runs-on: ubuntu-18.04 - needs: [unit-tests, snippets-tests] + timeout-minutes: 30 + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - uses: actions/setup-node@v1.4.4 + with: + node-version: "12" + - uses: ./.github/actions/dead-links + + + documentation-production: + name: Documentation - Deploy to production + runs-on: ubuntu-18.04 + timeout-minutes: 30 + needs: [lint, unit-tests, documentation-dead-links, documentation-snippets-tests] steps: - uses: actions/checkout@v2 - name: Cache node modules @@ -71,7 +107,7 @@ jobs: deploy-bintray: name: Deploy to Bintray - needs: [unit-tests, snippets-tests, doc-master] + needs: [lint, unit-tests, documentation-dead-links, documentation-snippets-tests, documentation-production] runs-on: ubuntu-18.04 timeout-minutes: 30 steps: @@ -81,3 +117,6 @@ jobs: java-version: "8" architecture: x64 - uses: ./.github/actions/deploy + with: + BINTRAY_USER: ${{ secrets.BINTRAY_USER }} + BINTRAY_KEY: ${{ secrets.BINTRAY_KEY }} From 15916226df9aeaea2a131f5295dc9578d25dee92 Mon Sep 17 00:00:00 2001 From: Alexandre Bouthinon Date: Fri, 22 Jan 2021 00:24:08 +0100 Subject: [PATCH 10/11] Test ktlint failure in CI --- src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt index 2ab644c7..12171221 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt @@ -14,7 +14,7 @@ class AuthController(kuzzle: Kuzzle) : BaseController(kuzzle) { ): CompletableFuture { val query = KuzzleMap().apply { put("controller", "auth") - put("action", "checkRights") + put("action", "checkRights") put("body", requestPayload) } return kuzzle From f045b2e2f5055f4944f873185754f17445f3ceda Mon Sep 17 00:00:00 2001 From: Alexandre Bouthinon Date: Fri, 22 Jan 2021 00:25:33 +0100 Subject: [PATCH 11/11] Revert fake ktlint bad formating (it's working) --- src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt b/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt index 12171221..2ab644c7 100644 --- a/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt +++ b/src/main/kotlin/io/kuzzle/sdk/controllers/AuthController.kt @@ -14,7 +14,7 @@ class AuthController(kuzzle: Kuzzle) : BaseController(kuzzle) { ): CompletableFuture { val query = KuzzleMap().apply { put("controller", "auth") - put("action", "checkRights") + put("action", "checkRights") put("body", requestPayload) } return kuzzle