From c2c1cf6907a7b800a1d8f51213cfd05720b13543 Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Fri, 4 Mar 2022 10:42:48 +0100 Subject: [PATCH] fix(java): solve oneOf using a custom generator APIC-300 (#125) --- .github/actions/cache/action.yml | 7 +- .github/workflows/check.yml | 22 +- .prettierignore | 1 + Dockerfile | 3 + clients/algoliasearch-client-java-2 | 2 +- .../base.tsconfig.json | 0 .../clients.config.json | 0 config/openapitools-java-cts.json | 9 + config/openapitools-java.json | 21 + .../release.config.json | 0 generators/build.gradle | 21 + generators/settings.gradle | 1 + .../algolia/codegen/AlgoliaJavaGenerator.java | 173 +++ .../algolia/codegen/GenerationException.java | 7 + .../codegen/cts/AlgoliaCtsGenerator.java | 172 +++ .../com/algolia/codegen/cts/CTSException.java | 7 + .../codegen/cts/EscapeQuotesLambda.java | 15 + .../codegen/cts/ParametersWithDataType.java | 326 +++++ .../java/com/algolia/codegen/cts/Request.java | 67 ++ .../org.openapitools.codegen.CodegenConfig | 2 + .../gradle/wrapper/gradle-wrapper.properties | 2 +- openapitools.json | 2 +- .../main/java/com/algolia/playground/App.java | 8 +- playground/javascript/browser/tsconfig.json | 2 +- playground/javascript/node/tsconfig.json | 2 +- scripts/config.ts | 2 +- scripts/cts/generate.ts | 13 +- scripts/generate.ts | 12 +- scripts/post-gen/java.sh | 37 - scripts/pre-gen/java.sh | 15 - scripts/release/common.ts | 6 +- scripts/release/process-release.ts | 16 +- scripts/tsconfig.json | 2 +- specs/analytics/common/schemas/getTopHits.yml | 9 +- .../common/schemas/getTopSearches.yml | 9 +- specs/analytics/paths/search/getTopHits.yml | 4 +- .../analytics/paths/search/getTopSearches.yml | 4 +- specs/bundled/analytics.yml | 24 +- specs/bundled/recommend.yml | 16 +- specs/bundled/search.yml | 110 +- specs/common/schemas/SearchParams.yml | 15 +- specs/search/common/enums.yml | 5 + specs/search/paths/advanced/getLogs.yml | 5 +- .../paths/dictionaries/common/parameters.yml | 7 +- specs/search/paths/keys/common/schemas.yml | 35 +- specs/search/paths/objects/common/schemas.yml | 28 +- specs/search/paths/objects/partialUpdate.yml | 5 +- .../java/EchoResponse.mustache | 42 +- templates/java/JSON.mustache | 470 ++------ .../libraries/okhttp-gson/ApiClient.mustache | 39 +- .../java/libraries/okhttp-gson/api.mustache | 6 +- templates/java/model.mustache | 4 - templates/java/oneof_interface.mustache | 56 +- templates/java/openapi.mustache | 1 - templates/java/pojo.mustache | 2 +- .../methods/requests/search/addApiKey.json | 1 - .../requests/search/addOrUpdateObject.json | 1 - .../methods/requests/search/appendSource.json | 1 - .../methods/requests/search/assignUserId.json | 1 - tests/CTS/methods/requests/search/batch.json | 8 +- .../requests/search/batchAssignUserIds.json | 1 - .../search/batchDictionaryEntries.json | 64 +- .../methods/requests/search/batchRules.json | 18 +- tests/CTS/methods/requests/search/browse.json | 1 - .../CTS/methods/requests/search/deleteBy.json | 1 - .../methods/requests/search/getObjects.json | 2 - .../requests/search/multipleBatch.json | 8 +- .../requests/search/multipleQueries.json | 12 +- .../requests/search/operationIndex.json | 6 +- .../requests/search/partialUpdateObject.json | 20 +- .../requests/search/replaceSources.json | 1 - .../methods/requests/search/saveObject.json | 1 - .../CTS/methods/requests/search/saveRule.json | 9 +- .../methods/requests/search/saveSynonym.json | 6 +- .../methods/requests/search/saveSynonyms.json | 12 +- tests/CTS/methods/requests/search/search.json | 1 - .../search/searchDictionaryEntries.json | 2 - .../requests/search/searchForFacetValues.json | 1 - .../methods/requests/search/searchRules.json | 1 - .../requests/search/searchUserIds.json | 1 - .../search/setDictionarySettings.json | 8 - .../methods/requests/search/setSettings.json | 1 - .../methods/requests/search/updateApiKey.json | 1 - .../templates/java/generateParams.mustache | 4 +- .../requests/templates/java/requests.mustache | 10 +- tests/output/java/.openapi-generator-ignore | 0 .../algolia/methods/requests/search.test.java | 1044 ++++++++--------- .../src/methods/requests/search.test.ts | 32 +- tests/output/javascript/tsconfig.json | 2 +- website/docs/commonTestSuite.md | 9 +- 90 files changed, 1784 insertions(+), 1378 deletions(-) rename base.tsconfig.json => config/base.tsconfig.json (100%) rename clients.config.json => config/clients.config.json (100%) create mode 100644 config/openapitools-java-cts.json create mode 100644 config/openapitools-java.json rename release.config.json => config/release.config.json (100%) create mode 100644 generators/build.gradle create mode 100644 generators/settings.gradle create mode 100644 generators/src/main/java/com/algolia/codegen/AlgoliaJavaGenerator.java create mode 100644 generators/src/main/java/com/algolia/codegen/GenerationException.java create mode 100644 generators/src/main/java/com/algolia/codegen/cts/AlgoliaCtsGenerator.java create mode 100644 generators/src/main/java/com/algolia/codegen/cts/CTSException.java create mode 100644 generators/src/main/java/com/algolia/codegen/cts/EscapeQuotesLambda.java create mode 100644 generators/src/main/java/com/algolia/codegen/cts/ParametersWithDataType.java create mode 100644 generators/src/main/java/com/algolia/codegen/cts/Request.java create mode 100644 generators/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig delete mode 100755 scripts/post-gen/java.sh delete mode 100755 scripts/pre-gen/java.sh rename scripts/post-gen/javaEchoResponse.mustache => templates/java/EchoResponse.mustache (50%) delete mode 100644 templates/java/openapi.mustache create mode 100644 tests/output/java/.openapi-generator-ignore diff --git a/.github/actions/cache/action.yml b/.github/actions/cache/action.yml index 66a1345811..1d29987842 100644 --- a/.github/actions/cache/action.yml +++ b/.github/actions/cache/action.yml @@ -110,7 +110,7 @@ runs: if: ${{ inputs.job == 'cts' }} uses: actions/cache@v2 with: - path: /home/runner/work/api-clients-automation/api-clients-automation/clients/algoliasearch-client-java-2/target + path: /home/runner/work/api-clients-automation/api-clients-automation/clients/algoliasearch-client-java-2 key: ${{ runner.os }}-${{ env.CACHE_VERSION }}-java-client-${{ hashFiles('clients/algoliasearch-client-java-2/**') }}-${{ hashFiles('specs/bundled/search.yml') }} # setup yarn @@ -134,3 +134,8 @@ runs: if: ${{ inputs.language == 'java' || inputs.job == 'cts' }} shell: bash run: curl -L "https://github.com/google/google-java-format/releases/download/v1.13.0/google-java-format-1.13.0-all-deps.jar" > /tmp/java-formatter.jar + + - name: Download openapi generator jar for java (TODO REMOVE) + if: ${{ inputs.language == 'java' || inputs.job == 'cts' }} + shell: bash + run: curl -L "https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.4.0/openapi-generator-cli-5.4.0.jar" > /tmp/openapi-generator-cli.jar diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index eaddee6210..34926a2683 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -142,12 +142,6 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' && matrix.client.name != 'algoliasearch' run: yarn cli generate javascript ${{ matrix.client.name }} - - name: Check diff with pushed client - if: steps.cache.outputs.cache-hit != 'true' - run: | - git status - exit $(git status --porcelain ${{ matrix.client.folder }} | wc -l) - - name: Build ${{ matrix.client.name }} client if: steps.cache.outputs.cache-hit != 'true' run: yarn cli build clients javascript ${{ matrix.client.name }} @@ -178,19 +172,13 @@ jobs: id: cache uses: actions/cache@v2 with: - path: '/home/runner/work/api-clients-automation/api-clients-automation/${{ matrix.client.folder }}/target' - key: ${{ runner.os }}-${{ env.CACHE_VERSION }}-java-client-${{ matrix.client.name }}-${{ hashFiles(format('{0}/**', matrix.client.folder)) }}-${{ hashFiles(format('specs/bundled/{0}.yml', matrix.client.name)) }} + path: '/home/runner/work/api-clients-automation/api-clients-automation/${{ matrix.client.folder }}' + key: ${{ runner.os }}-${{ env.CACHE_VERSION }}-java-client-${{ hashFiles(format('{0}/**', matrix.client.folder)) }}-${{ hashFiles(format('specs/bundled/{0}.yml', matrix.client.name)) }} - name: Generate ${{ matrix.client.name }} client if: steps.cache.outputs.cache-hit != 'true' run: yarn cli generate java ${{ matrix.client.name }} - - name: Check diff with pushed client - if: steps.cache.outputs.cache-hit != 'true' - run: | - git status - exit $(git status --porcelain ${{ matrix.client.folder }} | wc -l) - - name: Build ${{ matrix.client.name }} client if: steps.cache.outputs.cache-hit != 'true' run: yarn cli build clients java ${{ matrix.client.name }} @@ -221,12 +209,6 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' run: yarn cli generate php ${{ matrix.client.name }} - - name: Check diff with pushed client - if: steps.cache.outputs.cache-hit != 'true' - run: | - git status - exit $(git status --porcelain ${{ matrix.client.folder }} | wc -l) - - name: Build ${{ matrix.client.name }} client if: steps.cache.outputs.cache-hit != 'true' run: yarn cli build clients php ${{ matrix.client.name }} diff --git a/.prettierignore b/.prettierignore index 1521c8b765..de4d1f007d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1 +1,2 @@ dist +node_modules diff --git a/Dockerfile b/Dockerfile index b567072464..de045f51b4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,6 +10,9 @@ ENV JAVA_HOME=/usr/lib/jvm/default-jvm # Java formatter ADD https://github.com/google/google-java-format/releases/download/v1.13.0/google-java-format-1.13.0-all-deps.jar /tmp/java-formatter.jar +# openapi generator jar (TODO: REMOVE) +ADD https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.4.0/openapi-generator-cli-5.4.0.jar /tmp/openapi-generator-cli.jar + # PHP dependencies RUN apk add -U composer php8 php8-tokenizer php8-dom php8-xml php8-xmlwriter diff --git a/clients/algoliasearch-client-java-2 b/clients/algoliasearch-client-java-2 index 33defb6573..bd87197236 160000 --- a/clients/algoliasearch-client-java-2 +++ b/clients/algoliasearch-client-java-2 @@ -1 +1 @@ -Subproject commit 33defb6573f9ab00c3e78d90d35bd7a25845ce0f +Subproject commit bd8719723646211776a012391be29274687a2724 diff --git a/base.tsconfig.json b/config/base.tsconfig.json similarity index 100% rename from base.tsconfig.json rename to config/base.tsconfig.json diff --git a/clients.config.json b/config/clients.config.json similarity index 100% rename from clients.config.json rename to config/clients.config.json diff --git a/config/openapitools-java-cts.json b/config/openapitools-java-cts.json new file mode 100644 index 0000000000..8cb33abe13 --- /dev/null +++ b/config/openapitools-java-cts.json @@ -0,0 +1,9 @@ +{ + "generatorName": "algolia-cts", + "templateDir": "tests/CTS/methods/requests/templates/java", + "outputDir": "tests/output/java", + "artifactId": "java-tests", + "groupId": "com.algolia", + "invokerPackage": "com.algolia", + "inputSpec": "specs/bundled/search.yml" +} diff --git a/config/openapitools-java.json b/config/openapitools-java.json new file mode 100644 index 0000000000..a891ec42e2 --- /dev/null +++ b/config/openapitools-java.json @@ -0,0 +1,21 @@ +{ + "generatorName": "algolia-java", + "templateDir": "templates/java/", + "outputDir": "clients/algoliasearch-client-java-2", + "artifactId": "algoliasearch-client-java-2", + "groupId": "com.algolia", + "apiPackage": "com.algolia.search", + "invokerPackage": "com.algolia", + "modelPackage": "com.algolia.model.search", + "library": "okhttp-gson", + "inputSpec": "specs/bundled/search.yml", + "gitHost": "algolia", + "gitUserId": "algolia", + "gitRepoId": "algoliasearch-client-java-2", + "additionalProperties": { + "sourceFolder": "algoliasearch-core", + "java8": true, + "dateLibrary": "java8", + "packageName": "algoliasearch-client-java-2" + } +} diff --git a/release.config.json b/config/release.config.json similarity index 100% rename from release.config.json rename to config/release.config.json diff --git a/generators/build.gradle b/generators/build.gradle new file mode 100644 index 0000000000..795d70a9c7 --- /dev/null +++ b/generators/build.gradle @@ -0,0 +1,21 @@ +plugins { + id 'java' +} + +group = 'org.openapitools' +version = '1.0.0' +description = 'algolia-java-openapi-generator' +java.sourceCompatibility = JavaVersion.VERSION_1_8 + +repositories { + mavenCentral() +} + +dependencies { + compileOnly 'org.openapitools:openapi-generator:5.4.0' + compileOnly 'org.yaml:snakeyaml:1.19' +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} diff --git a/generators/settings.gradle b/generators/settings.gradle new file mode 100644 index 0000000000..22f1bf52de --- /dev/null +++ b/generators/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'algolia-java-openapi-generator' diff --git a/generators/src/main/java/com/algolia/codegen/AlgoliaJavaGenerator.java b/generators/src/main/java/com/algolia/codegen/AlgoliaJavaGenerator.java new file mode 100644 index 0000000000..406084ae20 --- /dev/null +++ b/generators/src/main/java/com/algolia/codegen/AlgoliaJavaGenerator.java @@ -0,0 +1,173 @@ +package com.algolia.codegen; + +import org.openapitools.codegen.*; +import org.openapitools.codegen.languages.JavaClientCodegen; +import org.openapitools.codegen.utils.ModelUtils; +import org.yaml.snakeyaml.Yaml; + +import java.util.*; +import java.util.Map.Entry; +import java.io.FileInputStream; +import java.net.URL; + +import io.swagger.v3.oas.models.media.Schema; + +@SuppressWarnings("unchecked") +public class AlgoliaJavaGenerator extends JavaClientCodegen { + /** + * Configures a friendly name for the generator. This will be used by the + * generator + * to select the library with the -g flag. + * + * @return the friendly name for the generator + */ + @Override + public String getName() { + return "algolia-java"; + } + + /** + * Inject server info into the client to generate the right URL + */ + private void generateServer(Map client) { + String clientName = (String) client.get("pathPrefix"); + Yaml yaml = new Yaml(); + try { + Map spec = yaml.load(new FileInputStream("specs/" + clientName + "/spec.yml")); + List> servers = (List>) spec.get("servers"); + + boolean hasRegionalHost = false; + boolean fallbackToAliasHost = false; + + boolean isEuHost = false; + boolean isDeHost = false; + String host = ""; + String topLevelDomain = ""; + + for (Map server : servers) { + if (!server.containsKey("url")) { + throw new GenerationException("Invalid server, does not contains 'url'"); + } + + if (!server.containsKey("variables")) { + continue; + } + + Map> variables = (Map>) server.get("variables"); + + if (!variables.containsKey("region") || !variables.get("region").containsKey("enum")) { + continue; + } + ArrayList enums = (ArrayList) variables.get("region").get("enum"); + hasRegionalHost = true; + + URL url = new URL((String) server.get("url")); + + if (!fallbackToAliasHost) { + // Determine if the current URL with `region` also have an alias without + // variables. + fallbackToAliasHost = true; + } + + if (enums.contains("eu")) { + isEuHost = true; + } + + if (enums.contains("de")) { + isDeHost = true; + } + + // This is used for hosts like `insights` that uses `.io` + String[] hostParts = url.getHost().split("\\."); + host = hostParts[0]; + topLevelDomain = hostParts[hostParts.length - 1]; + } + client.put("hasRegionalHost", hasRegionalHost); + client.put("fallbackToAliasHost", fallbackToAliasHost); + client.put("isEuHost", isEuHost); + client.put("isDeHost", isDeHost); + client.put("host", host); + client.put("topLevelDomain", topLevelDomain); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Provides an opportunity to inspect and modify operation data before the code + * is generated. + */ + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + Map results = super.postProcessOperationsWithModels(objs, allModels); + Map client = (Map) results.get("operations"); + + generateServer(client); + + return results; + } + + @Override + public Map postProcessAllModels(Map objs) { + Map models = super.postProcessAllModels(objs); + + for (Object modelContainer : models.values()) { + CodegenModel model = ((Map>>) modelContainer).get("models").get(0) + .get("model"); + if (!model.oneOf.isEmpty()) { + model.vendorExtensions.put("x-is-one-of-interface", true); + } + } + + return models; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Map bundle = super.postProcessSupportingFileData(objs); + List> apis = ((Map>>) bundle.get("apiInfo")).get("apis"); + for (Map api : apis) { + List operations = ((Map>) api.get("operations")) + .get("operation"); + + for (CodegenOperation ope : operations) { + ope.returnType = ope.returnType.replace("Map<", "HashMap<").replace("List<", "ArrayList<"); + } + } + return bundle; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + @Override + public String getHelp() { + return "Generates an algolia-java client library."; + } + + public AlgoliaJavaGenerator() { + super(); + + supportingFiles.add(new SupportingFile("EchoResponse.mustache", + "algoliasearch-core/com/algolia/utils/echo", + "EchoResponse.java")); + + // Prevent all useless file to generate + apiTestTemplateFiles.clear(); + modelTestTemplateFiles.clear(); + apiDocTemplateFiles.clear(); + modelDocTemplateFiles.clear(); + } + + @Override + public String toDefaultValue(Schema schema) { + // Replace the {} from openapi with new Object() + if (ModelUtils.isObjectSchema(schema) && schema.getDefault() != null) { + return "new Object()"; + } + return super.toDefaultValue(schema); + } +} diff --git a/generators/src/main/java/com/algolia/codegen/GenerationException.java b/generators/src/main/java/com/algolia/codegen/GenerationException.java new file mode 100644 index 0000000000..52d34b335c --- /dev/null +++ b/generators/src/main/java/com/algolia/codegen/GenerationException.java @@ -0,0 +1,7 @@ +package com.algolia.codegen; + +public class GenerationException extends Exception { + public GenerationException(String message) { + super(message); + } +} diff --git a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCtsGenerator.java b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCtsGenerator.java new file mode 100644 index 0000000000..fc2ad5cfc1 --- /dev/null +++ b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCtsGenerator.java @@ -0,0 +1,172 @@ +package com.algolia.codegen.cts; + +import org.openapitools.codegen.*; + +import java.util.*; +import java.util.Map.Entry; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.google.common.collect.ImmutableMap.Builder; +import com.samskivert.mustache.Mustache.Lambda; + +import java.io.File; +import java.io.IOException; + +import io.swagger.v3.core.util.Json; + +@SuppressWarnings("unchecked") +public class AlgoliaCtsGenerator extends DefaultCodegen { + // cache the models + private final Map models = new HashMap<>(); + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see org.openapitools.codegen.CodegenType + */ + @Override + public CodegenType getTag() { + return CodegenType.OTHER; + } + + /** + * Configures a friendly name for the generator. This will be used by the + * generator + * to select the library with the -g flag. + * + * @return the friendly name for the generator + */ + @Override + public String getName() { + return "algolia-cts"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates the CTS"; + } + + @Override + public Map postProcessAllModels(Map objs) { + Map mod = super.postProcessAllModels(objs); + for (Entry entry : mod.entrySet()) { + List innerModel = ((Map>) entry.getValue()).get("models"); + if (!innerModel.isEmpty()) { + models.put(entry.getKey(), (CodegenModel) ((Map) innerModel.get(0)).get("model")); + } + } + return mod; + } + + public AlgoliaCtsGenerator() { + super(); + supportingFiles + .add(new SupportingFile("requests.mustache", "src/test/java/com/algolia/methods/requests", "search.test.java")); + } + + @Override + protected Builder addMustacheLambdas() { + Builder lambdas = super.addMustacheLambdas(); + + lambdas.put("escapequotes", new EscapeQuotesLambda()); + return lambdas; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Map cts = null; + try { + cts = loadCTS(); + + Map operations = buildOperations(objs).get("Search"); + + Map bundle = super.postProcessSupportingFileData(objs); + + // We can put whatever we want in the bundle, and it will be accessible in the + // template + bundle.put("client", "SearchApi"); + + List blocks = new ArrayList<>(); + ParametersWithDataType paramsType = new ParametersWithDataType(models); + + for (Entry entry : cts.entrySet()) { + if (!operations.containsKey(entry.getKey())) { + throw new CTSException("operationId " + entry.getKey() + " does not exist in the spec"); + } + CodegenOperation op = operations.get(entry.getKey()); + + List tests = new ArrayList<>(); + for (int i = 0; i < entry.getValue().length; i++) { + Map test = paramsType.buildJSONForRequest(entry.getValue()[i], op, i); + tests.add(test); + } + Map testObj = new HashMap<>(); + testObj.put("tests", tests); + blocks.add(testObj); + } + bundle.put("blocks", blocks); + + return bundle; + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + return null; + } + + private Map loadCTS() throws JsonParseException, JsonMappingException, IOException { + TreeMap cts = new TreeMap<>(); + File dir = new File("tests/CTS/methods/requests/search"); + for (File f : dir.listFiles()) { + cts.put(f.getName().replace(".json", ""), Json.mapper().readValue(f, Request[].class)); + } + return cts; + } + + // Client -> operationId -> CodegenOperation + private HashMap> buildOperations(Map objs) { + HashMap> result = new HashMap<>(); + List> apis = ((Map>>) objs.get("apiInfo")).get("apis"); + for (Map api : apis) { + String apiName = (String) api.get("baseName"); + List operations = ((Map>) api.get("operations")) + .get("operation"); + + HashMap allOp = new HashMap<>(); + for (CodegenOperation ope : operations) { + allOp.put(ope.operationId, ope); + } + result.put(apiName, allOp); + } + return result; + } + + /** + * override with any special text escaping logic to handle unsafe + * characters so as to avoid code injection + * + * @param input String to be cleaned up + * @return string with unsafe characters removed or escaped + */ + @Override + public String escapeUnsafeCharacters(String input) { + return input; + } + + /** + * Escape single and/or double quote to avoid code injection + * + * @param input String to be cleaned up + * @return string with quotation mark removed or escaped + */ + public String escapeQuotationMark(String input) { + return input.replace("\"", "\\\""); + } +} diff --git a/generators/src/main/java/com/algolia/codegen/cts/CTSException.java b/generators/src/main/java/com/algolia/codegen/cts/CTSException.java new file mode 100644 index 0000000000..ba3765a6ff --- /dev/null +++ b/generators/src/main/java/com/algolia/codegen/cts/CTSException.java @@ -0,0 +1,7 @@ +package com.algolia.codegen.cts; + +public class CTSException extends Exception { + public CTSException(String message) { + super(message); + } +} diff --git a/generators/src/main/java/com/algolia/codegen/cts/EscapeQuotesLambda.java b/generators/src/main/java/com/algolia/codegen/cts/EscapeQuotesLambda.java new file mode 100644 index 0000000000..a66dfa10e8 --- /dev/null +++ b/generators/src/main/java/com/algolia/codegen/cts/EscapeQuotesLambda.java @@ -0,0 +1,15 @@ +package com.algolia.codegen.cts; + +import java.io.IOException; +import java.io.Writer; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; + +public class EscapeQuotesLambda implements Mustache.Lambda { + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + String text = fragment.execute(); + writer.write(text.replace("\"", "\\\"")); + } +} diff --git a/generators/src/main/java/com/algolia/codegen/cts/ParametersWithDataType.java b/generators/src/main/java/com/algolia/codegen/cts/ParametersWithDataType.java new file mode 100644 index 0000000000..7f5d717511 --- /dev/null +++ b/generators/src/main/java/com/algolia/codegen/cts/ParametersWithDataType.java @@ -0,0 +1,326 @@ +package com.algolia.codegen.cts; + +import java.util.*; +import java.util.Map.Entry; + +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenResponse; +import org.openapitools.codegen.IJsonSchemaValidationProperties; + +import io.swagger.v3.core.util.Json; + +@SuppressWarnings("unchecked") +public class ParametersWithDataType { + private final Map models; + + public ParametersWithDataType(Map models) { + this.models = models; + } + + public Map buildJSONForRequest(Request req, CodegenOperation ope, int testIndex) + throws CTSException { + Map test = new HashMap<>(); + test.put("method", req.method); + test.put("testName", req.testName == null ? req.method : req.testName); + test.put("testIndex", testIndex); + test.put("request", req.request); + + List parametersWithDataType = new ArrayList<>(); + + // special case if there is only bodyParam which is not an array + if (ope.allParams.size() == 1 && ope.bodyParams.size() == 1 && !ope.bodyParam.isArray) { + parametersWithDataType.add(traverseParams(ope.bodyParam.paramName, req.parameters, ope.bodyParam, "", 0)); + } else { + for (Entry param : req.parameters.entrySet()) { + CodegenParameter specParam = null; + for (CodegenParameter sp : ope.allParams) { + if (sp.paramName.equals(param.getKey())) { + specParam = sp; + break; + } + } + if (specParam == null) { + throw new CTSException("Parameter " + param.getKey() + " not found in the root parameter"); + } + parametersWithDataType.add(traverseParams(param.getKey(), param.getValue(), specParam, "", 0)); + } + } + + test.put("parametersWithDataType", parametersWithDataType); + return test; + } + + private Map traverseParams(String paramName, Object param, IJsonSchemaValidationProperties spec, + String parent, int suffix) + throws CTSException { + String baseType = getTypeName(spec); + if (baseType == null) { + throw new CTSException("Cannot determine type of " + paramName + " (value: " + param + ")"); + } + + boolean isCodegenModel = spec instanceof CodegenModel; + + if (!isCodegenModel) { + // don't overwrite it if it's already a model + // sometimes it's in lowercase for some reason + String lowerBaseType = baseType.substring(0, 1).toLowerCase() + baseType.substring(1); + if (models.containsKey(baseType)) { + // get the real model if possible + spec = models.get(baseType); + } else if (models.containsKey(lowerBaseType)) { + spec = models.get(lowerBaseType); + } + isCodegenModel = spec instanceof CodegenModel; + } + + String finalParamName = paramName; + if (paramName.startsWith("_")) { + finalParamName = paramName.substring(1); + } + + Map testOutput = createDefaultOutput(); + testOutput.put("key", finalParamName); + testOutput.put("parentSuffix", suffix - 1); + testOutput.put("suffix", suffix); + testOutput.put("parent", parent); + testOutput.put("objectName", baseType.substring(0, 1).toUpperCase() + baseType.substring(1)); + + if (spec.getIsArray()) { + handleArray(paramName, param, testOutput, spec, suffix); + } else if (isEnum(spec)) { + handleEnum(param, testOutput); + } else if (spec.getIsModel() || isCodegenModel) { + // recursive object + handleModel(paramName, param, testOutput, spec, baseType, parent, suffix); + } else if (baseType.equals("Object")) { + // not var, no item, pure free form + handleObject(paramName, param, testOutput, spec, suffix); + } else if (spec.getIsMap()) { + // free key but only one type + handleMap(paramName, param, testOutput, spec, suffix); + } else { + handlePrimitive(param, testOutput); + } + return testOutput; + } + + private Map createDefaultOutput() { + Map testOutput = new HashMap<>(); + + // we need to set all types to false otherwise mustache will read the one from + // the parent context and run into a infinite loop + testOutput.put("isObject", false); + testOutput.put("isArray", false); + testOutput.put("isFreeFormObject", false); + testOutput.put("isString", false); + testOutput.put("isInteger", false); + testOutput.put("isDouble", false); + testOutput.put("isBoolean", false); + testOutput.put("isEnum", false); + + return testOutput; + } + + private void handleArray(String paramName, Object param, Map testOutput, + IJsonSchemaValidationProperties spec, int suffix) throws CTSException { + List items = (List) param; + + List values = new ArrayList<>(); + for (int i = 0; i < items.size(); i++) { + values.add(traverseParams(paramName + "_" + i, items.get(i), spec.getItems(), paramName, suffix + 1)); + } + + testOutput.put("isArray", true); + testOutput.put("value", values); + } + + private void handleEnum(Object param, Map testOutput) { + testOutput.put("isEnum", true); + testOutput.put("value", param); + } + + private void handleModel(String paramName, Object param, Map testOutput, + IJsonSchemaValidationProperties spec, String baseType, String parent, int suffix) throws CTSException { + assert (spec.getHasVars()); + assert (spec.getItems() == null); + + if (spec instanceof CodegenModel && ((CodegenModel) spec).oneOf.size() > 0) { + // find a discriminator to handle oneOf + CodegenModel model = (CodegenModel) spec; + IJsonSchemaValidationProperties match = findMatchingOneOf(param, model); + testOutput.clear(); + testOutput.putAll(traverseParams(paramName, param, match, parent, suffix)); + testOutput.put("oneOfModel", baseType); + return; + } + + Map vars = (Map) param; + List values = new ArrayList<>(); + for (Entry entry : vars.entrySet()) { + IJsonSchemaValidationProperties varSpec = null; + for (CodegenProperty vs : spec.getVars()) { + if (vs.baseName.equals(entry.getKey())) { + varSpec = vs; + break; + } + } + if (varSpec == null) { + throw new CTSException("Parameter " + entry.getKey() + " not found in " + paramName + + ". You might have a type conflict in the spec for " + baseType); + } + + values.add(traverseParams(entry.getKey(), entry.getValue(), varSpec, paramName, suffix + 1)); + } + testOutput.put("isObject", true); + testOutput.put("value", values); + } + + private void handleObject(String paramName, Object param, Map testOutput, + IJsonSchemaValidationProperties spec, int suffix) throws CTSException { + assert (!spec.getHasVars()); + assert (spec.getItems() == null); + + Map vars = (Map) param; + + List values = new ArrayList<>(); + for (Entry entry : vars.entrySet()) { + CodegenParameter objSpec = new CodegenParameter(); + objSpec.dataType = inferDataType(entry.getValue(), objSpec, null); + values.add(traverseParams(entry.getKey(), entry.getValue(), objSpec, paramName, suffix + 1)); + } + + testOutput.put("isFreeFormObject", true); + testOutput.put("value", values); + } + + private void handleMap(String paramName, Object param, Map testOutput, + IJsonSchemaValidationProperties spec, int suffix) throws CTSException { + assert (!spec.getHasVars()); + assert (spec.getItems() != null); + + Map vars = (Map) param; + + List values = new ArrayList<>(); + for (Entry entry : vars.entrySet()) { + values.add(traverseParams(entry.getKey(), entry.getValue(), spec.getItems(), paramName, suffix + 1)); + } + + testOutput.put("isFreeFormObject", true); + testOutput.put("value", values); + } + + private void handlePrimitive(Object param, Map testOutput) throws CTSException { + inferDataType(param, null, testOutput); + testOutput.put("value", param); + } + + private String getTypeName(IJsonSchemaValidationProperties param) { + if (param instanceof CodegenParameter) { + return ((CodegenParameter) param).dataType; + } + if (param instanceof CodegenProperty) { + return ((CodegenProperty) param).dataType; + } + if (param instanceof CodegenModel) { + return ((CodegenModel) param).classname; + } + if (param instanceof CodegenResponse) { + return ((CodegenResponse) param).dataType; + } + return null; + } + + private boolean isEnum(IJsonSchemaValidationProperties param) { + if (param instanceof CodegenParameter) { + return ((CodegenParameter) param).isEnum; + } + if (param instanceof CodegenProperty) { + return ((CodegenProperty) param).isEnum; + } + if (param instanceof CodegenModel) { + return ((CodegenModel) param).isEnum; + } + return false; + } + + private String inferDataType(Object param, CodegenParameter spec, Map output) throws CTSException { + switch (param.getClass().getSimpleName()) { + case "String": + if (spec != null) + spec.setIsString(true); + if (output != null) + output.put("isString", true); + return "String"; + case "Integer": + if (spec != null) + spec.setIsNumber(true); + if (output != null) + output.put("isInteger", true); + return "Integer"; + case "Double": + if (spec != null) + spec.setIsNumber(true); + if (output != null) + output.put("isDouble", true); + return "Double"; + case "Boolean": + if (spec != null) + spec.setIsBoolean(true); + if (output != null) + output.put("isBoolean", true); + return "Boolean"; + default: + throw new CTSException("Unknown type: " + param.getClass().getSimpleName()); + } + } + + private IJsonSchemaValidationProperties findMatchingOneOf(Object param, CodegenModel model) throws CTSException { + if (param instanceof Map) { + // for object, check which has the most of property in common + int maxCount = 0; + CodegenModel bestOneOf = model.interfaceModels.get(0); + for (CodegenModel oneOf : model.interfaceModels) { + if (oneOf.vars.size() == 0) { + continue; + } + + Map map = (Map) param; + int commonCount = 0; + for (String prop : map.keySet()) { + for (CodegenProperty propOneOf : oneOf.vars) { + if (prop.equals(propOneOf.name)) { + commonCount++; + } + } + } + if (commonCount > maxCount) { + maxCount = commonCount; + bestOneOf = oneOf; + } + } + return bestOneOf; + } + if (param instanceof List) { + // no idea for list + return null; + } + + CodegenParameter maybeMatch = new CodegenParameter(); + String paramType = inferDataType(param, maybeMatch, null); + maybeMatch.dataType = paramType; + + for (String oneOfName : model.oneOf) { + if (oneOfName.equals(paramType)) { + return maybeMatch; + } + } + for (CodegenModel oneOf : model.interfaceModels) { + if (oneOf.dataType.equals(paramType)) + return oneOf; + } + return null; + } +} diff --git a/generators/src/main/java/com/algolia/codegen/cts/Request.java b/generators/src/main/java/com/algolia/codegen/cts/Request.java new file mode 100644 index 0000000000..bd9433949b --- /dev/null +++ b/generators/src/main/java/com/algolia/codegen/cts/Request.java @@ -0,0 +1,67 @@ +package com.algolia.codegen.cts; + +import java.io.IOException; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonRawValue; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.TreeNode; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +public class Request { + public String testName; + public String method; + public Map parameters; + public RequestProp request; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Request {\n"); + sb.append(" testName: ").append(testName).append("\n"); + sb.append(" method: ").append(method).append("\n"); + sb.append(" parameters: ").append(parameters).append("\n"); + sb.append(" request: ").append(request).append("\n"); + sb.append("}"); + return sb.toString(); + } +} + +class RequestProp { + public String path; + public String method; + + @JsonDeserialize(using = RawDeserializer.class) + public Object data; + + @JsonDeserialize(using = RawDeserializer.class) + public Object searchParams; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class RequestProp {\n"); + sb.append(" path: ").append(path).append("\n"); + sb.append(" method: ").append(method).append("\n"); + sb.append(" data: ").append(data).append("\n"); + sb.append(" searchParams: ").append(searchParams).append("\n"); + sb.append("}"); + return sb.toString(); + } +} + +// Output json to raw string with quotes +class RawDeserializer extends JsonDeserializer { + + @Override + public String deserialize(JsonParser jp, DeserializationContext ctxt) + throws IOException, JsonProcessingException { + + TreeNode tree = jp.getCodec().readTree(jp); + return tree.toString(); + } +} diff --git a/generators/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/generators/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig new file mode 100644 index 0000000000..b7d2d08d16 --- /dev/null +++ b/generators/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -0,0 +1,2 @@ +com.algolia.codegen.AlgoliaJavaGenerator +com.algolia.codegen.cts.AlgoliaCtsGenerator diff --git a/gradle/gradle/wrapper/gradle-wrapper.properties b/gradle/gradle/wrapper/gradle-wrapper.properties index 2e6e5897b5..41dfb87909 100644 --- a/gradle/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/openapitools.json b/openapitools.json index c7f40ae154..6c5f68e2a4 100644 --- a/openapitools.json +++ b/openapitools.json @@ -231,7 +231,7 @@ "groupId": "com.algolia", "apiPackage": "com.algolia.search", "invokerPackage": "com.algolia", - "modelPackage": "com.algolia.model", + "modelPackage": "com.algolia.model.search", "library": "okhttp-gson", "glob": "specs/bundled/search.yml", "gitHost": "algolia", diff --git a/playground/java/src/main/java/com/algolia/playground/App.java b/playground/java/src/main/java/com/algolia/playground/App.java index 0915b58dee..071830147f 100644 --- a/playground/java/src/main/java/com/algolia/playground/App.java +++ b/playground/java/src/main/java/com/algolia/playground/App.java @@ -1,8 +1,9 @@ package com.algolia.playground; -import com.algolia.model.*; +import com.algolia.model.search.*; import com.algolia.search.SearchApi; import com.algolia.ApiException; +import com.algolia.utils.echo.*; import io.github.cdimascio.dotenv.Dotenv; @@ -12,10 +13,11 @@ public static void main(String[] args) { SearchApi client = new SearchApi(dotenv.get("ALGOLIA_APPLICATION_ID"), dotenv.get("ALGOLIA_SEARCH_KEY")); String indexName = dotenv.get("SEARCH_INDEX"); - SearchParams params = new SearchParams(); + SearchParamsObject params = new SearchParamsObject(); + params.setAroundRadius(AroundRadius.of(5)); params.setQuery(dotenv.get("SEARCH_QUERY")); try { - SearchResponse result = client.search(indexName, params); + SearchResponse result = client.search(indexName, SearchParams.of(params)); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling SearchApi#search"); diff --git a/playground/javascript/browser/tsconfig.json b/playground/javascript/browser/tsconfig.json index 0ab41dfc98..54152b47cb 100644 --- a/playground/javascript/browser/tsconfig.json +++ b/playground/javascript/browser/tsconfig.json @@ -1,5 +1,5 @@ { - "extends": "../../../base.tsconfig.json", + "extends": "../../../config/base.tsconfig.json", "compilerOptions": { "outDir": "dist", "lib": ["dom"] diff --git a/playground/javascript/node/tsconfig.json b/playground/javascript/node/tsconfig.json index 6170db0681..ff404088c6 100644 --- a/playground/javascript/node/tsconfig.json +++ b/playground/javascript/node/tsconfig.json @@ -1,5 +1,5 @@ { - "extends": "../../../base.tsconfig.json", + "extends": "../../../config/base.tsconfig.json", "compilerOptions": { "outDir": "dist" }, diff --git a/scripts/config.ts b/scripts/config.ts index 25baddcb41..f4558505a9 100644 --- a/scripts/config.ts +++ b/scripts/config.ts @@ -1,4 +1,4 @@ -import clientsConfig from '../clients.config.json'; +import clientsConfig from '../config/clients.config.json'; export function getLanguageFolder(language: string): string { return clientsConfig[language].folder; diff --git a/scripts/cts/generate.ts b/scripts/cts/generate.ts index e2b416835c..f6200e7e15 100644 --- a/scripts/cts/generate.ts +++ b/scripts/cts/generate.ts @@ -1,4 +1,4 @@ -import { toAbsolutePath } from '../common'; +import { run, toAbsolutePath } from '../common'; import { getTestOutputFolder } from '../config'; import { formatter } from '../formatter'; import { createSpinner } from '../oraLog'; @@ -14,10 +14,19 @@ async function ctsGenerate( createSpinner(`generating CTS for ${generator.key}`, verbose).start().info(); switch (generator.language) { case 'javascript': - case 'java': await generateRequestsTests(generator, verbose); await generateClientTests(generator, verbose); break; + case 'java': + // eslint-disable-next-line no-warning-comments + // TODO: We can remove this once https://github.com/OpenAPITools/openapi-generator-cli/issues/439 is fixed, + // and just call it with `yarn openapi-generator-cli --custom-generator=generators/build/libs/algolia-java-openapi-generator-1.0.0.jar` + await run( + `./gradle/gradlew --no-daemon -p generators assemble && \ + java -cp /tmp/openapi-generator-cli.jar:generators/build/libs/algolia-java-openapi-generator-1.0.0.jar -ea org.openapitools.codegen.OpenAPIGenerator generate -c config/openapitools-java-cts.json`, + { verbose } + ); + break; default: } } diff --git a/scripts/generate.ts b/scripts/generate.ts index 39cfb119b0..c3b19c65f4 100644 --- a/scripts/generate.ts +++ b/scripts/generate.ts @@ -19,9 +19,19 @@ async function preGen( } async function generateClient( - { key }: Generator, + { language, key }: Generator, verbose?: boolean ): Promise { + if (language === 'java') { + // eslint-disable-next-line no-warning-comments + // TODO: We can remove this once https://github.com/OpenAPITools/openapi-generator-cli/issues/439 is fixed + await run( + `./gradle/gradlew --no-daemon -p generators assemble && \ + java -cp /tmp/openapi-generator-cli.jar:generators/build/libs/algolia-java-openapi-generator-1.0.0.jar -ea org.openapitools.codegen.OpenAPIGenerator generate -c config/openapitools-java.json`, + { verbose } + ); + return; + } await run(`yarn openapi-generator-cli generate --generator-key ${key}`, { verbose, }); diff --git a/scripts/post-gen/java.sh b/scripts/post-gen/java.sh deleted file mode 100755 index 17f1548a84..0000000000 --- a/scripts/post-gen/java.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -# Break on non-zero code -set -e - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -# Move to the root (easier to locate other scripts) -cd ${DIR}/../.. - -FOLDER=$1 - -# Restore the oneOf spec -mv ./specs/search/paths/search/search.yml.bak ./specs/search/paths/search/search.yml -mv ./specs/search/paths/objects/deleteBy.yml.bak ./specs/search/paths/objects/deleteBy.yml -mv ./specs/search/paths/objects/partialUpdate.yml.bak ./specs/search/paths/objects/partialUpdate.yml - -# Replace {} (OpenAPI default) with new Object -find "$FOLDER" -type f -name "*.java" | xargs sed -i -e 's~= {}~= new Object()~g' - -# Create a special class for the OneOf integer string (not complete yet, juste here for compilation) -echo "package com.algolia.model;public class OneOfintegerstring {}" > $FOLDER/algoliasearch-core/com/algolia/model/OneOfintegerstring.java -echo 'package com.algolia.model;import com.google.gson.annotations.SerializedName;public class OneOfstringbuiltInOperation { @SerializedName("_operation") private String _operation; @SerializedName("value") private String value;public void set_operation(String op){_operation = op;} public void setValue(String value) {this.value=value;} }' > $FOLDER/algoliasearch-core/com/algolia/model/OneOfstringbuiltInOperation.java - -# Generate types for the EchoRequester, to be able to keep the correct response type on the API method. - -# Extract the normal response to extend it -responses=($(grep -o 'public .*ApiCallback<.*>' $FOLDER/algoliasearch-core/com/algolia/**/*Api.java | sed 's/public.*ApiCallback$//; s/ //; s/^Map $FOLDER/algoliasearch-core/com/algolia/utils/echo/EchoResponse.java diff --git a/scripts/pre-gen/java.sh b/scripts/pre-gen/java.sh deleted file mode 100755 index 2c5fb11e59..0000000000 --- a/scripts/pre-gen/java.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -# Break on non-zero code -set -e - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -# Move to the root (easier to locate other scripts) -cd ${DIR}/../.. - -# Remove the oneOf in the spec until it's supported (https://github.com/OpenAPITools/openapi-generator/issues/10880). - -# Remove the oneOf and only keep the last $ref -perl -0777 -i.bak -pe "s/oneOf[\s\S]*- \$ref(?!.*- \$ref)//g" ./specs/search/paths/search/search.yml -perl -0777 -i.bak -pe "s/oneOf[\s\S]*- \$ref(?!.*- \$ref)//g" ./specs/search/paths/objects/deleteBy.yml -perl -0777 -i.bak -pe "s/oneOf[\s\S]*- \$ref(?!.*- \$ref)//g" ./specs/search/paths/objects/partialUpdate.yml diff --git a/scripts/release/common.ts b/scripts/release/common.ts index a112debcb7..512159f826 100644 --- a/scripts/release/common.ts +++ b/scripts/release/common.ts @@ -1,4 +1,4 @@ -import config from '../../release.config.json'; +import config from '../../config/release.config.json'; export const RELEASED_TAG = config.releasedTag; export const MAIN_BRANCH = config.mainBranch; @@ -9,6 +9,10 @@ export function getTargetBranch(language: string): string { return config.targetBranch[language] || config.defaultTargetBranch; } +export function getGitAuthor(): { name: string; email: string } { + return config.gitAuthor; +} + export function getMarkdownSection(markdown: string, title: string): string { const levelIndicator = title.split(' ')[0]; // e.g. `##` const lines = markdown diff --git a/scripts/release/process-release.ts b/scripts/release/process-release.ts index adad33b4c5..b8e4dd819c 100755 --- a/scripts/release/process-release.ts +++ b/scripts/release/process-release.ts @@ -4,10 +4,9 @@ import fsp from 'fs/promises'; import dotenv from 'dotenv'; import execa from 'execa'; -import clientsConfig from '../../clients.config.json'; import openapitools from '../../openapitools.json'; -import releaseConfig from '../../release.config.json'; import { toAbsolutePath, run, exists, getGitHubUrl } from '../common'; +import { getLanguageFolder } from '../config'; import { RELEASED_TAG, @@ -15,6 +14,7 @@ import { REPO, getMarkdownSection, getTargetBranch, + getGitAuthor, } from './common'; import TEXT from './text'; @@ -92,8 +92,8 @@ async function updateOpenApiTools( } async function configureGitHubAuthor(cwd?: string): Promise { - await run(`git config user.name "${releaseConfig.gitAuthor.name}"`, { cwd }); - await run(`git config user.email "${releaseConfig.gitAuthor.email}"`, { + await run(`git config user.name "${getGitAuthor().name}"`, { cwd }); + await run(`git config user.email "${getGitAuthor().email}"`, { cwd, }); } @@ -129,7 +129,7 @@ async function processRelease(): Promise { for (const lang of langsToReleaseOrUpdate) { // prepare the submodule - const clientPath = toAbsolutePath(clientsConfig[lang].folder); + const clientPath = toAbsolutePath(getLanguageFolder(lang)); const targetBranch = getTargetBranch(lang); await run(`git checkout ${targetBranch}`, { cwd: clientPath }); await run(`git pull origin ${targetBranch}`, { cwd: clientPath }); @@ -143,7 +143,7 @@ async function processRelease(): Promise { // update changelog const changelogPath = toAbsolutePath( - `${clientsConfig[lang].folder}/CHANGELOG.md` + `${getLanguageFolder(lang)}/CHANGELOG.md` ); const existingContent = (await exists(changelogPath)) ? (await fsp.readFile(changelogPath)).toString() @@ -177,13 +177,13 @@ async function processRelease(): Promise { } // add the new reference of the submodule in the monorepo - await run(`git add ${clientsConfig[lang].folder}`); + await run(`git add ${getLanguageFolder(lang)}`); } // We push commits from submodules AFTER all the generations are done. // Otherwise, we will end up having broken release. for (const lang of langsToReleaseOrUpdate) { - const clientPath = toAbsolutePath(clientsConfig[lang].folder); + const clientPath = toAbsolutePath(getLanguageFolder(lang)); const targetBranch = getTargetBranch(lang); await run(`git push origin ${targetBranch}`, { cwd: clientPath }); diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json index ab90a217cc..eacb895f56 100644 --- a/scripts/tsconfig.json +++ b/scripts/tsconfig.json @@ -1,5 +1,5 @@ { - "extends": "../base.tsconfig.json", + "extends": "../config/base.tsconfig.json", "compilerOptions": { "typeRoots": ["../node_modules/@types"], "types": ["node", "jest"], diff --git a/specs/analytics/common/schemas/getTopHits.yml b/specs/analytics/common/schemas/getTopHits.yml index fd5e48396e..6214fc1f78 100644 --- a/specs/analytics/common/schemas/getTopHits.yml +++ b/specs/analytics/common/schemas/getTopHits.yml @@ -1,4 +1,4 @@ -getTopHitsResponse: +topHitsResponse: type: object additionalProperties: false required: @@ -19,7 +19,7 @@ getTopHitsResponse: count: $ref: ../../../common/parameters.yml#/count -getTopHitsResponseWithAnalytics: +topHitsResponseWithAnalytics: type: object additionalProperties: false required: @@ -54,3 +54,8 @@ getTopHitsResponseWithAnalytics: $ref: '../parameters.yml#/clickCount' conversionCount: $ref: '../parameters.yml#/conversionCount' + +getTopHitsResponse: + oneOf: + - $ref: '#/topHitsResponse' + - $ref: '#/topHitsResponseWithAnalytics' diff --git a/specs/analytics/common/schemas/getTopSearches.yml b/specs/analytics/common/schemas/getTopSearches.yml index 24ede2268e..51270f3209 100644 --- a/specs/analytics/common/schemas/getTopSearches.yml +++ b/specs/analytics/common/schemas/getTopSearches.yml @@ -1,4 +1,4 @@ -getTopSearchesResponse: +topSearchesResponse: type: object additionalProperties: false required: @@ -22,7 +22,7 @@ getTopSearchesResponse: nbHits: $ref: ../../../search/common/schemas/SearchResponse.yml#/nbHits -getTopSearchesResponseWithAnalytics: +topSearchesResponseWithAnalytics: type: object additionalProperties: false required: @@ -63,3 +63,8 @@ getTopSearchesResponseWithAnalytics: $ref: '../parameters.yml#/conversionCount' nbHits: $ref: ../../../search/common/schemas/SearchResponse.yml#/nbHits + +getTopSearchesResponse: + oneOf: + - $ref: '#/topSearchesResponse' + - $ref: '#/topSearchesResponseWithAnalytics' diff --git a/specs/analytics/paths/search/getTopHits.yml b/specs/analytics/paths/search/getTopHits.yml index 53060831b0..a132b78c77 100644 --- a/specs/analytics/paths/search/getTopHits.yml +++ b/specs/analytics/paths/search/getTopHits.yml @@ -17,9 +17,7 @@ get: content: application/json: schema: - oneOf: - - $ref: '../../common/schemas/getTopHits.yml#/getTopHitsResponse' - - $ref: '../../common/schemas/getTopHits.yml#/getTopHitsResponseWithAnalytics' + $ref: '../../common/schemas/getTopHits.yml#/getTopHitsResponse' '400': $ref: ../../../common/responses/BadRequest.yml '402': diff --git a/specs/analytics/paths/search/getTopSearches.yml b/specs/analytics/paths/search/getTopSearches.yml index 78cf649f52..7f24daf24d 100644 --- a/specs/analytics/paths/search/getTopSearches.yml +++ b/specs/analytics/paths/search/getTopSearches.yml @@ -18,9 +18,7 @@ get: content: application/json: schema: - oneOf: - - $ref: '../../common/schemas/getTopSearches.yml#/getTopSearchesResponse' - - $ref: '../../common/schemas/getTopSearches.yml#/getTopSearchesResponseWithAnalytics' + $ref: '../../common/schemas/getTopSearches.yml#/getTopSearchesResponse' '400': $ref: ../../../common/responses/BadRequest.yml '402': diff --git a/specs/bundled/analytics.yml b/specs/bundled/analytics.yml index 52c5efbad7..dcf7000d5c 100644 --- a/specs/bundled/analytics.yml +++ b/specs/bundled/analytics.yml @@ -145,7 +145,7 @@ components: type: integer description: Number of hits that the search query matched. example: 20 - getTopSearchesResponse: + topSearchesResponse: type: object additionalProperties: false required: @@ -188,7 +188,7 @@ components: conversionCount: type: integer description: The number of converted clicks. - getTopSearchesResponseWithAnalytics: + topSearchesResponseWithAnalytics: type: object additionalProperties: false required: @@ -229,13 +229,17 @@ components: $ref: '#/components/schemas/conversionCount' nbHits: $ref: '#/components/schemas/nbHits' + getTopSearchesResponse: + oneOf: + - $ref: '#/components/schemas/topSearchesResponse' + - $ref: '#/components/schemas/topSearchesResponseWithAnalytics' date: type: string description: Date of the event. hit: description: The hit. type: string - getTopHitsResponse: + topHitsResponse: type: object additionalProperties: false required: @@ -255,7 +259,7 @@ components: $ref: '#/components/schemas/hit' count: $ref: '#/components/schemas/count' - getTopHitsResponseWithAnalytics: + topHitsResponseWithAnalytics: type: object additionalProperties: false required: @@ -290,6 +294,10 @@ components: $ref: '#/components/schemas/clickCount' conversionCount: $ref: '#/components/schemas/conversionCount' + getTopHitsResponse: + oneOf: + - $ref: '#/components/schemas/topHitsResponse' + - $ref: '#/components/schemas/topHitsResponseWithAnalytics' attribute: description: The attribute. type: string @@ -574,9 +582,7 @@ paths: content: application/json: schema: - oneOf: - - $ref: '#/components/schemas/getTopSearchesResponse' - - $ref: '#/components/schemas/getTopSearchesResponseWithAnalytics' + $ref: '#/components/schemas/getTopSearchesResponse' '400': $ref: '#/components/responses/BadRequest' '402': @@ -900,9 +906,7 @@ paths: content: application/json: schema: - oneOf: - - $ref: '#/components/schemas/getTopHitsResponse' - - $ref: '#/components/schemas/getTopHitsResponseWithAnalytics' + $ref: '#/components/schemas/getTopHitsResponse' '400': $ref: '#/components/responses/BadRequest' '402': diff --git a/specs/bundled/recommend.yml b/specs/bundled/recommend.yml index e102dbf76e..0a36dcfc5a 100644 --- a/specs/bundled/recommend.yml +++ b/specs/bundled/recommend.yml @@ -56,6 +56,14 @@ components: type: integer description: Specify the page to retrieve. default: 0 + aroundRadius: + description: Define the maximum radius for a geo search (in meters). + oneOf: + - type: integer + minimum: 1 + - type: string + enum: + - all baseSearchParams: type: object additionalProperties: false @@ -146,13 +154,7 @@ components: from the requester's IP address. default: false aroundRadius: - description: Define the maximum radius for a geo search (in meters). - oneOf: - - type: integer - minimum: 1 - - type: string - enum: - - all + $ref: '#/components/schemas/aroundRadius' aroundPrecision: type: integer description: >- diff --git a/specs/bundled/search.yml b/specs/bundled/search.yml index ccdffbe8b2..50a87ae95a 100644 --- a/specs/bundled/search.yml +++ b/specs/bundled/search.yml @@ -117,11 +117,7 @@ components: description: The dictionary to search in. required: true schema: - enum: - - plurals - - stopwords - - compounds - type: string + $ref: '#/components/schemas/dictionaryType' Page: in: query name: page @@ -172,6 +168,14 @@ components: type: integer description: Specify the page to retrieve. default: 0 + aroundRadius: + description: Define the maximum radius for a geo search (in meters). + oneOf: + - type: integer + minimum: 1 + - type: string + enum: + - all baseSearchParams: type: object additionalProperties: false @@ -262,13 +266,7 @@ components: from the requester's IP address. default: false aroundRadius: - description: Define the maximum radius for a geo search (in meters). - oneOf: - - type: integer - minimum: 1 - - type: string - enum: - - all + $ref: '#/components/schemas/aroundRadius' aroundPrecision: type: integer description: >- @@ -1006,6 +1004,17 @@ components: updatedAt: type: string description: Date of last update (ISO-8601 format). + builtInOperationType: + type: string + enum: + - Increment + - Decrement + - Add + - Remove + - AddUnique + - IncrementFrom + - IncrementSet + description: The operation to apply on the attribute. builtInOperation: type: object description: >- @@ -1014,16 +1023,7 @@ components: additionalProperties: false properties: _operation: - type: string - enum: - - Increment - - Decrement - - Add - - Remove - - AddUnique - - IncrementFrom - - IncrementSet - description: The operation to apply on the attribute. + $ref: '#/components/schemas/builtInOperationType' value: type: string description: >- @@ -1032,6 +1032,10 @@ components: required: - _operation - value + attributeOrBuiltInOperation: + oneOf: + - $ref: '#/components/schemas/attribute' + - $ref: '#/components/schemas/builtInOperation' action: type: string enum: @@ -1202,6 +1206,23 @@ components: required: - hits - nbHits + acl: + type: string + enum: + - addObject + - analytics + - browse + - deleteObject + - deleteIndex + - editSettings + - listIndexes + - logs + - personalization + - recommendation + - search + - seeUnretrievableAttributes + - settings + - usage apiKey: type: object description: Api Key object. @@ -1212,22 +1233,7 @@ components: description: Set of permissions associated with the key. default: [] items: - type: string - enum: - - addObject - - analytics - - browse - - deleteObject - - deleteIndex - - editSettings - - listIndexes - - logs - - personalization - - recommendation - - search - - seeUnretrievableAttributes - - settings - - usage + $ref: '#/components/schemas/acl' description: type: string description: >- @@ -1520,6 +1526,12 @@ components: type: integer default: 20 description: Maximum number of hits in a page. Minimum is 1, maximum is 1000. + dictionaryType: + type: string + enum: + - plurals + - stopwords + - compounds dictionaryAction: type: string enum: @@ -1670,6 +1682,14 @@ components: type: array items: $ref: '#/components/schemas/source' + logType: + type: string + enum: + - all + - query + - build + - error + default: all operationType: type: string enum: @@ -2431,15 +2451,12 @@ paths: application/json: schema: type: array - additionalProperties: false items: type: object title: attributeToUpdate description: Attribute to update. additionalProperties: - oneOf: - - $ref: '#/components/schemas/attribute' - - $ref: '#/components/schemas/builtInOperation' + $ref: '#/components/schemas/attributeOrBuiltInOperation' responses: '200': $ref: '#/components/responses/UpdatedAtWithObjectId' @@ -4005,20 +4022,13 @@ paths: schema: type: string nullable: true - default: null - name: type in: query description: >- Type of log entries to retrieve. When omitted, all log entries are retrieved. schema: - type: string - enum: - - all - - query - - build - - error - default: all + $ref: '#/components/schemas/logType' responses: '200': description: OK diff --git a/specs/common/schemas/SearchParams.yml b/specs/common/schemas/SearchParams.yml index 77da247bd7..36adff4d76 100644 --- a/specs/common/schemas/SearchParams.yml +++ b/specs/common/schemas/SearchParams.yml @@ -96,12 +96,7 @@ baseSearchParams: description: Search for entries around a given location automatically computed from the requester's IP address. default: false aroundRadius: - description: Define the maximum radius for a geo search (in meters). - oneOf: - - type: integer - minimum: 1 - - type: string - enum: [all] + $ref: '#/aroundRadius' aroundPrecision: type: integer description: Precision of geo search (in meters), to add grouping by geo location to the ranking formula. @@ -196,3 +191,11 @@ cursor: type: string description: Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. example: jMDY3M2MwM2QwMWUxMmQwYWI0ZTN + +aroundRadius: + description: Define the maximum radius for a geo search (in meters). + oneOf: + - type: integer + minimum: 1 + - type: string + enum: [all] diff --git a/specs/search/common/enums.yml b/specs/search/common/enums.yml index c90345a657..7c758d4f8d 100644 --- a/specs/search/common/enums.yml +++ b/specs/search/common/enums.yml @@ -27,3 +27,8 @@ dictionaryEntryState: enum: [enabled, disabled] default: enabled description: The state of the dictionary entry. + +logType: + type: string + enum: [all, query, build, error] + default: all diff --git a/specs/search/paths/advanced/getLogs.yml b/specs/search/paths/advanced/getLogs.yml index d9b5c43921..3e8971dae7 100644 --- a/specs/search/paths/advanced/getLogs.yml +++ b/specs/search/paths/advanced/getLogs.yml @@ -22,14 +22,11 @@ get: schema: type: string nullable: true - default: null - name: type in: query description: Type of log entries to retrieve. When omitted, all log entries are retrieved. schema: - type: string - enum: [all, query, build, error] - default: all + $ref: ../../common/enums.yml#/logType responses: '200': description: OK diff --git a/specs/search/paths/dictionaries/common/parameters.yml b/specs/search/paths/dictionaries/common/parameters.yml index 626febc030..dba15e24ad 100644 --- a/specs/search/paths/dictionaries/common/parameters.yml +++ b/specs/search/paths/dictionaries/common/parameters.yml @@ -5,8 +5,11 @@ DictionaryName: description: The dictionary to search in. required: true schema: - enum: [plurals, stopwords, compounds] - type: string + $ref: '#/dictionaryType' + +dictionaryType: + type: string + enum: [plurals, stopwords, compounds] # misc language: diff --git a/specs/search/paths/keys/common/schemas.yml b/specs/search/paths/keys/common/schemas.yml index 50d93846e9..81f83d13c8 100644 --- a/specs/search/paths/keys/common/schemas.yml +++ b/specs/search/paths/keys/common/schemas.yml @@ -8,22 +8,7 @@ apiKey: description: Set of permissions associated with the key. default: [] items: - type: string - enum: - - addObject - - analytics - - browse - - deleteObject - - deleteIndex - - editSettings - - listIndexes - - logs - - personalization - - recommendation - - search - - seeUnretrievableAttributes - - settings - - usage + $ref: '#/acl' description: type: string @@ -88,3 +73,21 @@ addApiKeyResponse: required: - key - createdAt + +acl: + type: string + enum: + - addObject + - analytics + - browse + - deleteObject + - deleteIndex + - editSettings + - listIndexes + - logs + - personalization + - recommendation + - search + - seeUnretrievableAttributes + - settings + - usage diff --git a/specs/search/paths/objects/common/schemas.yml b/specs/search/paths/objects/common/schemas.yml index 5a445300f3..89ec42b7ba 100644 --- a/specs/search/paths/objects/common/schemas.yml +++ b/specs/search/paths/objects/common/schemas.yml @@ -10,6 +10,18 @@ action: - clear description: type of operation. +builtInOperationType: + type: string + enum: + - Increment + - Decrement + - Add + - Remove + - AddUnique + - IncrementFrom + - IncrementSet + description: The operation to apply on the attribute. + attribute: type: string description: Value of the attribute to be updated. @@ -20,19 +32,15 @@ builtInOperation: additionalProperties: false properties: _operation: - type: string - enum: - - Increment - - Decrement - - Add - - Remove - - AddUnique - - IncrementFrom - - IncrementSet - description: The operation to apply on the attribute. + $ref: '#/builtInOperationType' value: type: string description: the right-hand side argument to the operation, for example, increment or decrement step, value to add or remove. required: - _operation - value + +attributeOrBuiltInOperation: + oneOf: + - $ref: '#/attribute' + - $ref: '#/builtInOperation' diff --git a/specs/search/paths/objects/partialUpdate.yml b/specs/search/paths/objects/partialUpdate.yml index d894a70fdb..26aef3a52c 100644 --- a/specs/search/paths/objects/partialUpdate.yml +++ b/specs/search/paths/objects/partialUpdate.yml @@ -25,15 +25,12 @@ post: application/json: schema: type: array - additionalProperties: false items: type: object title: attributeToUpdate description: Attribute to update. additionalProperties: - oneOf: - - $ref: 'common/schemas.yml#/attribute' - - $ref: 'common/schemas.yml#/builtInOperation' + $ref: 'common/schemas.yml#/attributeOrBuiltInOperation' responses: '200': $ref: ../../../common/responses/UpdatedAtWithObjectId.yml diff --git a/scripts/post-gen/javaEchoResponse.mustache b/templates/java/EchoResponse.mustache similarity index 50% rename from scripts/post-gen/javaEchoResponse.mustache rename to templates/java/EchoResponse.mustache index 1d9694e6c5..6fc98aaf00 100644 --- a/scripts/post-gen/javaEchoResponse.mustache +++ b/templates/java/EchoResponse.mustache @@ -1,7 +1,7 @@ package com.algolia.utils.echo; import com.algolia.Pair; -import com.algolia.model.*; +import com.algolia.model.search.*; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -35,29 +35,33 @@ public class EchoResponse { return params; } - {{#responses}} - public static class {{{className}}} extends {{{superClass}}} implements EchoResponseInterface { - private Request request; + {{#apiInfo}}{{#apis}} + public static class {{baseName}}Echo { + {{#operations}}{{#operation}} + public static class {{#lambda.titlecase}}{{{operationId}}}{{/lambda.titlecase}} extends {{{returnType}}} implements EchoResponseInterface { + private Request request; - public {{{className}}}(Request request) { - this.request = request; - } + public {{#lambda.titlecase}}{{{operationId}}}{{/lambda.titlecase}}(Request request) { + this.request = request; + } - public String getPath() { - return request.url().encodedPath(); - } + public String getPath() { + return request.url().encodedPath(); + } - public String getMethod() { - return request.method(); - } + public String getMethod() { + return request.method(); + } - public String getBody() { - return parseRequestBody(request); - } + public String getBody() { + return parseRequestBody(request); + } - public List getQueryParams() { - return buildQueryParams(request); + public List getQueryParams() { + return buildQueryParams(request); + } } + {{/operation}}{{/operations}} } - {{/responses}} + {{/apis}}{{/apiInfo}} } diff --git a/templates/java/JSON.mustache b/templates/java/JSON.mustache index 00b5bd0d14..c412ab1b51 100644 --- a/templates/java/JSON.mustache +++ b/templates/java/JSON.mustache @@ -51,20 +51,18 @@ import io.gsonfire.GsonFireBuilder; import okio.ByteString; public class JSON { - private Gson gson; - private boolean isLenientOnJson = false; - private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); - private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); - {{#joda}} - private DateTimeTypeAdapter dateTimeTypeAdapter = new DateTimeTypeAdapter(); - private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - {{/joda}} - {{#jsr310}} - private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); - private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - {{/jsr310}} - private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private RetainFieldMapFactory mapAdapter = new RetainFieldMapFactory(); + private static Gson gson; + private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + private static RetainFieldMapFactory mapAdapter = new RetainFieldMapFactory(); + + static { + gson = createGson() + .registerTypeAdapter(Date.class, dateTypeAdapter) + .registerTypeAdapter(byte[].class, byteArrayAdapter) + .registerTypeAdapterFactory(mapAdapter) + .create(); + } public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -85,30 +83,8 @@ public class JSON { }) {{/discriminator}} {{/model}} - {{/models}} - ; - GsonBuilder builder = fireBuilder.createGsonBuilder(); - {{#disableHtmlEscaping}} - builder.disableHtmlEscaping(); - {{/disableHtmlEscaping}} - return builder; - } - - public JSON() { - gson = createGson() - .registerTypeAdapter(Date.class, dateTypeAdapter) - .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) - {{#joda}} - .registerTypeAdapter(DateTime.class, dateTimeTypeAdapter) - .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) - {{/joda}} - {{#jsr310}} - .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) - .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) - {{/jsr310}} - .registerTypeAdapter(byte[].class, byteArrayAdapter) - .registerTypeAdapterFactory(mapAdapter) - .create(); + {{/models}}; + return fireBuilder.createGsonBuilder(); } /** @@ -116,7 +92,7 @@ public class JSON { * * @return Gson */ - public Gson getGson() { + public static Gson getGson() { return gson; } @@ -126,14 +102,8 @@ public class JSON { * @param gson Gson * @return JSON */ - public JSON setGson(Gson gson) { - this.gson = gson; - return this; - } - - public JSON setLenientOnJson(boolean lenientOnJson) { - isLenientOnJson = lenientOnJson; - return this; + public static void setGson(Gson gon) { + gson = gon; } /** @@ -142,7 +112,7 @@ public class JSON { * @param obj Object * @return String representation of the JSON */ - public String serialize(Object obj) { + public static String serialize(Object obj) { return gson.toJson(obj); } @@ -154,20 +124,13 @@ public class JSON { * @param returnType The type to deserialize into * @return The deserialized Java object */ - public T deserialize(String body, Type returnType) { + public static T deserialize(String body, Type returnType) { try { - if (isLenientOnJson) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } + return gson.fromJson(body, returnType); } catch (JsonParseException e) { // Fallback processing when failed to parse JSON form response body: // return the response body string directly for the String return type; - if (returnType.equals(String.class)) { + if (returnType != null && returnType.equals(String.class)) { return (T) body; } else { throw (e); @@ -175,347 +138,94 @@ public class JSON { } } - /** - * Gson TypeAdapter for Byte Array type - */ - public class ByteArrayAdapter extends TypeAdapter { - - @Override - public void write(JsonWriter out, byte[] value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - out.value(ByteString.of(value).base64()); - } - } - - @Override - public byte[] read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String bytesAsBase64 = in.nextString(); - ByteString byteString = ByteString.decodeBase64(bytesAsBase64); - return byteString.toByteArray(); - } - } - } - - {{#joda}} - /** - * Gson TypeAdapter for Joda DateTime type - */ - public static class DateTimeTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public DateTimeTypeAdapter() { - this(new DateTimeFormatterBuilder() - .append(ISODateTimeFormat.dateTime().getPrinter(), ISODateTimeFormat.dateOptionalTimeParser().getParser()) - .toFormatter()); - } - - public DateTimeTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseDateTime(date); - } - } - } - - /** - * Gson TypeAdapter for Joda LocalDate type - */ - public class LocalDateTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public LocalDateTypeAdapter() { - this(ISODateTimeFormat.date()); - } - - public LocalDateTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); - } - } + public static void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); } +} - public JSON setDateTimeFormat(DateTimeFormatter dateFormat) { - dateTimeTypeAdapter.setFormat(dateFormat); - return this; - } +/** +* Gson TypeAdapter for Byte Array type +*/ +class ByteArrayAdapter extends TypeAdapter { - public JSON setLocalDateFormat(DateTimeFormatter dateFormat) { - localDateTypeAdapter.setFormat(dateFormat); - return this; +@Override +public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); } +} - {{/joda}} - {{#jsr310}} - /** - * Gson TypeAdapter for JSR310 OffsetDateTime type - */ - public static class OffsetDateTimeTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public OffsetDateTimeTypeAdapter() { - this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } - - public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, OffsetDateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public OffsetDateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - if (date.endsWith("+0000")) { - date = date.substring(0, date.length()-5) + "Z"; - } - return OffsetDateTime.parse(date, formatter); - } - } +@Override +public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); } +} +} - /** - * Gson TypeAdapter for JSR310 LocalDate type - */ - public class LocalDateTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; +/** +* Gson TypeAdapter for java.util.Date type +* If the dateFormat is null, ISO8601Utils will be used. +*/ +class DateTypeAdapter extends TypeAdapter { - public LocalDateTypeAdapter() { - this(DateTimeFormatter.ISO_LOCAL_DATE); - } +private DateFormat dateFormat; - public LocalDateTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } +public DateTypeAdapter() {} - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } +public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; +} - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } +public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; +} - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return LocalDate.parse(date, formatter); - } +@Override +public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); } + out.value(value); } +} - public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - offsetDateTimeTypeAdapter.setFormat(dateFormat); - return this; - } - - public JSON setLocalDateFormat(DateTimeFormatter dateFormat) { - localDateTypeAdapter.setFormat(dateFormat); - return this; - } - - {{/jsr310}} - /** - * Gson TypeAdapter for java.sql.Date type - * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used - * (more efficient than SimpleDateFormat). - */ - public static class SqlDateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public SqlDateTypeAdapter() {} - - public SqlDateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, java.sql.Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = date.toString(); - } - out.value(value); - } - } - - @Override - public java.sql.Date read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return new java.sql.Date(dateFormat.parse(date).getTime()); - } - return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); - } catch (ParseException e) { - throw new JsonParseException(e); +@Override +public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); } - } - } - } - - /** - * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, ISO8601Utils will be used. - */ - public static class DateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public DateTypeAdapter() {} - - public DateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = ISO8601Utils.format(date, true); + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); } - out.value(value); - } - } - - @Override - public Date read(JsonReader in) throws IOException { - try { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return dateFormat.parse(date); - } - return ISO8601Utils.parse(date, new ParsePosition(0)); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } catch (IllegalArgumentException e) { - throw new JsonParseException(e); - } } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); } - - public JSON setDateFormat(DateFormat dateFormat) { - dateTypeAdapter.setFormat(dateFormat); - return this; - } - - public JSON setSqlDateFormat(DateFormat dateFormat) { - sqlDateTypeAdapter.setFormat(dateFormat); - return this; - } +} } // https://stackoverflow.com/questions/21458468/gson-wont-properly-serialise-a-class-that-extends-hashmap diff --git a/templates/java/libraries/okhttp-gson/ApiClient.mustache b/templates/java/libraries/okhttp-gson/ApiClient.mustache index 991a5644dd..261530c058 100644 --- a/templates/java/libraries/okhttp-gson/ApiClient.mustache +++ b/templates/java/libraries/okhttp-gson/ApiClient.mustache @@ -32,15 +32,12 @@ public class ApiClient { private DateFormat dateFormat; - private JSON json; - private Requester requester; /* * Constructor for ApiClient with custom Requester */ public ApiClient(String appId, String apiKey, Requester requester) { - json = new JSON(); setUserAgent("{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}"); this.basePath = "https://" + appId + "-1.algolianet.com"; @@ -49,40 +46,10 @@ public class ApiClient { this.requester = requester; } - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - public DateFormat getDateFormat() { return dateFormat; } - public ApiClient setDateFormat(DateFormat dateFormat) { - this.json.setDateFormat(dateFormat); - return this; - } - - public ApiClient setLenientOnJson(boolean lenientOnJson) { - this.json.setLenientOnJson(lenientOnJson); - return this; - } - /** * Set the User-Agent header's value (by adding to the default header map). * @@ -203,7 +170,7 @@ public class ApiClient { return ""; } else if (param instanceof Date {{#joda}}|| param instanceof DateTime || param instanceof LocalDate{{/joda}}{{#jsr310}}|| param instanceof OffsetDateTime || param instanceof LocalDate{{/jsr310}}) { //Serialize to json string and remove the " enclosing characters - String jsonStr = json.serialize(param); + String jsonStr = JSON.serialize(param); return jsonStr.substring(1, jsonStr.length() - 1); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); @@ -399,7 +366,7 @@ public class ApiClient { contentType = "application/json"; } if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); + return JSON.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. return (T) respBody; @@ -428,7 +395,7 @@ public class ApiClient { } else if (isJsonMime(contentType)) { String content; if (obj != null) { - content = json.serialize(obj); + content = JSON.serialize(obj); } else { content = null; } diff --git a/templates/java/libraries/okhttp-gson/api.mustache b/templates/java/libraries/okhttp-gson/api.mustache index fc2753641e..f288023c54 100644 --- a/templates/java/libraries/okhttp-gson/api.mustache +++ b/templates/java/libraries/okhttp-gson/api.mustache @@ -13,7 +13,7 @@ import okhttp3.Request; import com.algolia.utils.*; import com.algolia.utils.echo.*; -import com.algolia.model.*; +import com.algolia.model.search.*; import java.lang.reflect.Type; {{^fullJavaUtil}} @@ -111,7 +111,7 @@ public class {{classname}} extends ApiClient { public {{#returnType}}{{{.}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { Call req = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null); if (req instanceof CallEcho) { - {{#returnType}}return new EchoResponse.{{#lambda.titlecase}}{{{operationId}}}{{/lambda.titlecase}}(((CallEcho)req).request());{{/returnType}} + {{#returnType}}return new EchoResponse.{{baseName}}Echo.{{#lambda.titlecase}}{{{operationId}}}{{/lambda.titlecase}}(((CallEcho)req).request());{{/returnType}} } Call call = (Call)req; {{#returnType}}Type returnType = new TypeToken<{{{.}}}>(){}.getType(); @@ -121,7 +121,7 @@ public class {{classname}} extends ApiClient { {{#optionalParams.0}} public {{#returnType}}{{{.}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}) throws ApiException { - {{#returnType}}return {{/returnType}}this.{{operationId}}({{#requiredParams}}{{paramName}}{{^-last}},{{/-last}}{{/requiredParams}}{{#requiredParams.0}},{{/requiredParams.0}}{{#optionalParams}}{{#defaultValue}}{{#isString}}"{{.}}"{{/isString}}{{^isString}}{{.}}{{/isString}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{^-last}},{{/-last}}{{/optionalParams}}); + {{#returnType}}return {{/returnType}}this.{{operationId}}({{#requiredParams}}{{paramName}}{{^-last}},{{/-last}}{{/requiredParams}}{{#requiredParams.0}},{{/requiredParams.0}}{{#optionalParams}}{{#schema}}{{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/schema}}{{^schema}}null{{/schema}}{{^-last}},{{/-last}}{{/optionalParams}}); } {{/optionalParams.0}} diff --git a/templates/java/model.mustache b/templates/java/model.mustache index bd1dc88ba7..13a53736c1 100644 --- a/templates/java/model.mustache +++ b/templates/java/model.mustache @@ -19,10 +19,6 @@ import javax.json.stream.JsonGenerator; import javax.json.stream.JsonParser; import javax.json.bind.annotation.JsonbProperty; {{/jsonb}} -{{#parcelableModel}} -import android.os.Parcelable; -import android.os.Parcel; -{{/parcelableModel}} {{#models}} {{#model}} diff --git a/templates/java/oneof_interface.mustache b/templates/java/oneof_interface.mustache index e2927410ff..1f9979e490 100644 --- a/templates/java/oneof_interface.mustache +++ b/templates/java/oneof_interface.mustache @@ -1,6 +1,54 @@ +import com.algolia.utils.CompoundType; +import com.algolia.JSON; + +import com.google.gson.TypeAdapter; +import com.google.gson.reflect.TypeToken; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +@JsonAdapter({{classname}}.Adapter.class) {{>additionalModelTypeAnnotations}} -public interface {{classname}} {{#vendorExtensions.x-implements}}{{#-first}}extends {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { - {{#discriminator}} - public {{propertyType}} {{propertyGetter}}(); - {{/discriminator}} +public abstract class {{classname}} implements CompoundType { + {{#oneOf}} + public static {{classname}} of({{.}} inside) { + return new {{classname}}{{.}}(inside); + } + + {{/oneOf}} + public abstract Object getInsideValue(); + + public static class Adapter extends TypeAdapter<{{classname}}> { + @Override + public void write( + final JsonWriter out, + final {{classname}} oneOf) throws IOException { + TypeAdapter runtimeTypeAdapter = (TypeAdapter) JSON.getGson() + .getAdapter(TypeToken.get(oneOf.getInsideValue().getClass())); + runtimeTypeAdapter.write(out, oneOf.getInsideValue()); + } + + @Override + public {{classname}} read(final JsonReader jsonReader) + throws IOException { + return null; + } + } } + +{{#oneOf}} +@JsonAdapter({{classname}}.Adapter.class) +class {{classname}}{{.}} extends {{classname}} { + private final {{.}} insideValue; + + {{classname}}{{.}}({{.}} insideValue) { + this.insideValue = insideValue; + } + + @Override + public {{.}} getInsideValue() { + return insideValue; + } +} +{{/oneOf}} diff --git a/templates/java/openapi.mustache b/templates/java/openapi.mustache deleted file mode 100644 index 34fbb53f33..0000000000 --- a/templates/java/openapi.mustache +++ /dev/null @@ -1 +0,0 @@ -{{{openapi-yaml}}} diff --git a/templates/java/pojo.mustache b/templates/java/pojo.mustache index bf46406f4a..479efd798d 100644 --- a/templates/java/pojo.mustache +++ b/templates/java/pojo.mustache @@ -4,7 +4,7 @@ */{{#isDeprecated}} @Deprecated{{/isDeprecated}} {{>additionalModelTypeAnnotations}} -public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{#-last}} {{/-last}}{{/vendorExtensions.x-implements}}{ +public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{ {{#serializableModel}} private static final long serialVersionUID = 1L; diff --git a/tests/CTS/methods/requests/search/addApiKey.json b/tests/CTS/methods/requests/search/addApiKey.json index 882e9c4f43..c503c2e0bb 100644 --- a/tests/CTS/methods/requests/search/addApiKey.json +++ b/tests/CTS/methods/requests/search/addApiKey.json @@ -2,7 +2,6 @@ { "method": "addApiKey", "parameters": { - "$objectName": "ApiKey", "acl": [ "search", "addObject" diff --git a/tests/CTS/methods/requests/search/addOrUpdateObject.json b/tests/CTS/methods/requests/search/addOrUpdateObject.json index 8ecab59078..c718ec67eb 100644 --- a/tests/CTS/methods/requests/search/addOrUpdateObject.json +++ b/tests/CTS/methods/requests/search/addOrUpdateObject.json @@ -5,7 +5,6 @@ "indexName": "indexName", "objectID": "uniqueID", "body": { - "$objectName": "Object", "key": "value" } }, diff --git a/tests/CTS/methods/requests/search/appendSource.json b/tests/CTS/methods/requests/search/appendSource.json index c936d0a41c..53b7a7940a 100644 --- a/tests/CTS/methods/requests/search/appendSource.json +++ b/tests/CTS/methods/requests/search/appendSource.json @@ -2,7 +2,6 @@ { "method": "appendSource", "parameters": { - "$objectName": "Source", "source": "theSource", "description": "theDescription" }, diff --git a/tests/CTS/methods/requests/search/assignUserId.json b/tests/CTS/methods/requests/search/assignUserId.json index 20275326f9..7abfe64b6c 100644 --- a/tests/CTS/methods/requests/search/assignUserId.json +++ b/tests/CTS/methods/requests/search/assignUserId.json @@ -4,7 +4,6 @@ "parameters": { "xAlgoliaUserID": "userID", "assignUserIdParams": { - "$objectName": "AssignUserIdParams", "cluster": "theCluster" } }, diff --git a/tests/CTS/methods/requests/search/batch.json b/tests/CTS/methods/requests/search/batch.json index 2907779501..fc28525200 100644 --- a/tests/CTS/methods/requests/search/batch.json +++ b/tests/CTS/methods/requests/search/batch.json @@ -4,16 +4,10 @@ "parameters": { "indexName": "theIndexName", "batchWriteParams": { - "$objectName": "BatchWriteParams", "requests": [ { - "$objectName": "BatchOperation", - "action": { - "$enumType": "Action", - "value": "delete" - }, + "action": "delete", "body": { - "$objectName": "Object", "key": "value" } } diff --git a/tests/CTS/methods/requests/search/batchAssignUserIds.json b/tests/CTS/methods/requests/search/batchAssignUserIds.json index 7d934f5543..0ed242e835 100644 --- a/tests/CTS/methods/requests/search/batchAssignUserIds.json +++ b/tests/CTS/methods/requests/search/batchAssignUserIds.json @@ -4,7 +4,6 @@ "parameters": { "xAlgoliaUserID": "userID", "batchAssignUserIdsParams": { - "$objectName": "BatchAssignUserIdsParams", "cluster": "theCluster", "users": [ "user1", diff --git a/tests/CTS/methods/requests/search/batchDictionaryEntries.json b/tests/CTS/methods/requests/search/batchDictionaryEntries.json index d8cca28eea..c4b8dfcb0a 100644 --- a/tests/CTS/methods/requests/search/batchDictionaryEntries.json +++ b/tests/CTS/methods/requests/search/batchDictionaryEntries.json @@ -5,28 +5,17 @@ "parameters": { "dictionaryName": "compounds", "batchDictionaryEntriesParams": { - "$objectName": "BatchDictionaryEntriesParams", "requests": [ { - "$objectName": "BatchDictionaryEntriesRequest", - "action": { - "$enumType": "DictionaryAction", - "value": "addEntry" - }, + "action": "addEntry", "body": { - "$objectName": "DictionaryEntry", "objectID": "1", "language": "en" } }, { - "$objectName": "BatchDictionaryEntriesRequest", - "action": { - "$enumType": "DictionaryAction", - "value": "deleteEntry" - }, + "action": "deleteEntry", "body": { - "$objectName": "DictionaryEntry", "objectID": "2", "language": "fr" } @@ -63,57 +52,40 @@ "parameters": { "dictionaryName": "compounds", "batchDictionaryEntriesParams": { - "$objectName": "BatchDictionaryEntriesParams", "clearExistingDictionaryEntries": false, "requests": [ { - "$objectName": "BatchDictionaryEntriesRequest", - "action": { - "$enumType": "DictionaryAction", - "value": "addEntry" - }, + "action": "addEntry", "body": { - "$objectName": "DictionaryEntry", "objectID": "1", "language": "en", - "word": "yo", + "word": "fancy", "words": [ - "yo", + "believe", "algolia" ], "decomposition": [ - "yo", + "trust", "algolia" ], - "state": { - "$enumType": "DictionaryEntryState", - "value": "enabled" - } + "state": "enabled" } }, { - "$objectName": "BatchDictionaryEntriesRequest", - "action": { - "$enumType": "DictionaryAction", - "value": "deleteEntry" - }, + "action": "deleteEntry", "body": { - "$objectName": "DictionaryEntry", "objectID": "2", "language": "fr", - "word": "salut", + "word": "humility", "words": [ - "salut", + "candor", "algolia" ], "decomposition": [ - "salut", + "grit", "algolia" ], - "state": { - "$enumType": "DictionaryEntryState", - "value": "enabled" - } + "state": "enabled" } } ] @@ -130,13 +102,13 @@ "body": { "objectID": "1", "language": "en", - "word": "yo", + "word": "fancy", "words": [ - "yo", + "believe", "algolia" ], "decomposition": [ - "yo", + "trust", "algolia" ], "state": "enabled" @@ -147,13 +119,13 @@ "body": { "objectID": "2", "language": "fr", - "word": "salut", + "word": "humility", "words": [ - "salut", + "candor", "algolia" ], "decomposition": [ - "salut", + "grit", "algolia" ], "state": "enabled" diff --git a/tests/CTS/methods/requests/search/batchRules.json b/tests/CTS/methods/requests/search/batchRules.json index acd26555c5..6d7653e0cd 100644 --- a/tests/CTS/methods/requests/search/batchRules.json +++ b/tests/CTS/methods/requests/search/batchRules.json @@ -5,43 +5,29 @@ "indexName": "indexName", "rule": [ { - "$objectName": "Rule", "objectID": "a-rule-id", "conditions": [ { - "$objectName": "Condition", "pattern": "smartphone", - "anchoring": { - "$enumType": "Anchoring", - "value": "contains" - } + "anchoring": "contains" } ], "consequence": { - "$objectName": "Consequence", "params": { - "$objectName": "ConsequenceParams", "filters": "category:smartphone" } } }, { - "$objectName": "Rule", "objectID": "a-second-rule-id", "conditions": [ { - "$objectName": "Condition", "pattern": "apple", - "anchoring": { - "$enumType": "Anchoring", - "value": "contains" - } + "anchoring": "contains" } ], "consequence": { - "$objectName": "Consequence", "params": { - "$objectName": "ConsequenceParams", "filters": "brand:apple" } } diff --git a/tests/CTS/methods/requests/search/browse.json b/tests/CTS/methods/requests/search/browse.json index 22f1f1c8b8..56fb3a8a25 100644 --- a/tests/CTS/methods/requests/search/browse.json +++ b/tests/CTS/methods/requests/search/browse.json @@ -16,7 +16,6 @@ "parameters": { "indexName": "indexName", "browseRequest": { - "$objectName": "BrowseRequest", "params": "query=foo&facetFilters=['bar']", "cursor": "cts" } diff --git a/tests/CTS/methods/requests/search/deleteBy.json b/tests/CTS/methods/requests/search/deleteBy.json index 6188cd02eb..4510f3cdee 100644 --- a/tests/CTS/methods/requests/search/deleteBy.json +++ b/tests/CTS/methods/requests/search/deleteBy.json @@ -4,7 +4,6 @@ "parameters": { "indexName": "theIndexName", "searchParams": { - "$objectName": "SearchParams", "query": "testQuery" } }, diff --git a/tests/CTS/methods/requests/search/getObjects.json b/tests/CTS/methods/requests/search/getObjects.json index a63a5caf61..ee802641f9 100644 --- a/tests/CTS/methods/requests/search/getObjects.json +++ b/tests/CTS/methods/requests/search/getObjects.json @@ -2,10 +2,8 @@ { "method": "getObjects", "parameters": { - "$objectName": "GetObjectsParams", "requests": [ { - "$objectName": "MultipleGetObjectsParams", "attributesToRetrieve": [ "attr1", "attr2" diff --git a/tests/CTS/methods/requests/search/multipleBatch.json b/tests/CTS/methods/requests/search/multipleBatch.json index 91f0fec9a7..71326b5669 100644 --- a/tests/CTS/methods/requests/search/multipleBatch.json +++ b/tests/CTS/methods/requests/search/multipleBatch.json @@ -2,16 +2,10 @@ { "method": "multipleBatch", "parameters": { - "$objectName": "BatchParams", "requests": [ { - "$objectName": "MultipleBatchOperation", - "action": { - "$enumType": "Action", - "value": "addObject" - }, + "action": "addObject", "body": { - "$objectName": "Object", "key": "value" }, "indexName": "theIndexName" diff --git a/tests/CTS/methods/requests/search/multipleQueries.json b/tests/CTS/methods/requests/search/multipleQueries.json index 5c18ccc6da..d994520843 100644 --- a/tests/CTS/methods/requests/search/multipleQueries.json +++ b/tests/CTS/methods/requests/search/multipleQueries.json @@ -2,24 +2,16 @@ { "method": "multipleQueries", "parameters": { - "$objectName": "MultipleQueriesParams", "requests": [ { - "$objectName": "MultipleQueries", "indexName": "theIndexName", "query": "test", - "type": { - "$enumType": "MultipleQueriesType", - "value": "facet" - }, + "type": "facet", "facet": "theFacet", "params": "testParam" } ], - "strategy": { - "$enumType": "MultipleQueriesStrategy", - "value": "stopIfEnoughMatches" - } + "strategy": "stopIfEnoughMatches" }, "request": { "path": "/1/indexes/*/queries", diff --git a/tests/CTS/methods/requests/search/operationIndex.json b/tests/CTS/methods/requests/search/operationIndex.json index c7fc12ae01..b8584dbdf6 100644 --- a/tests/CTS/methods/requests/search/operationIndex.json +++ b/tests/CTS/methods/requests/search/operationIndex.json @@ -4,11 +4,7 @@ "parameters": { "indexName": "theIndexName", "operationIndexParams": { - "$objectName": "OperationIndexParams", - "operation": { - "$enumType": "OperationType", - "value": "copy" - }, + "operation": "copy", "destination": "dest", "scope": [ "rules", diff --git a/tests/CTS/methods/requests/search/partialUpdateObject.json b/tests/CTS/methods/requests/search/partialUpdateObject.json index 413fa1e3a3..9cfcf77523 100644 --- a/tests/CTS/methods/requests/search/partialUpdateObject.json +++ b/tests/CTS/methods/requests/search/partialUpdateObject.json @@ -4,19 +4,10 @@ "parameters": { "indexName": "theIndexName", "objectID": "uniqueID", - "stringBuiltInOperation": [ + "attributeOrBuiltInOperation": [ { - "$objectName": "Object", - "id1": { - "$objectName": "Object", - "_operation": "AddUnique", - "value": "test1" - } - }, - { - "$objectName": "Object", + "id1": "test", "id2": { - "$objectName": "Object", "_operation": "AddUnique", "value": "test2" } @@ -29,12 +20,7 @@ "method": "POST", "data": [ { - "id1": { - "_operation": "AddUnique", - "value": "test1" - } - }, - { + "id1": "test", "id2": { "_operation": "AddUnique", "value": "test2" diff --git a/tests/CTS/methods/requests/search/replaceSources.json b/tests/CTS/methods/requests/search/replaceSources.json index 363ea44501..11d64ae1f2 100644 --- a/tests/CTS/methods/requests/search/replaceSources.json +++ b/tests/CTS/methods/requests/search/replaceSources.json @@ -4,7 +4,6 @@ "parameters": { "source": [ { - "$objectName": "Source", "source": "theSource", "description": "theDescription" } diff --git a/tests/CTS/methods/requests/search/saveObject.json b/tests/CTS/methods/requests/search/saveObject.json index b8c4f6a015..529ecbc6fa 100644 --- a/tests/CTS/methods/requests/search/saveObject.json +++ b/tests/CTS/methods/requests/search/saveObject.json @@ -4,7 +4,6 @@ "parameters": { "indexName": "theIndexName", "body": { - "$objectName": "Object", "objectID": "id", "test": "val" } diff --git a/tests/CTS/methods/requests/search/saveRule.json b/tests/CTS/methods/requests/search/saveRule.json index 62dbe32b85..5dbb735fb9 100644 --- a/tests/CTS/methods/requests/search/saveRule.json +++ b/tests/CTS/methods/requests/search/saveRule.json @@ -5,22 +5,15 @@ "indexName": "indexName", "objectID": "id1", "rule": { - "$objectName": "Rule", "objectID": "id1", "conditions": [ { - "$objectName": "Condition", "pattern": "apple", - "anchoring": { - "$enumType": "Anchoring", - "value": "contains" - } + "anchoring": "contains" } ], "consequence": { - "$objectName": "Consequence", "params": { - "$objectName": "ConsequenceParams", "filters": "brand:apple" } } diff --git a/tests/CTS/methods/requests/search/saveSynonym.json b/tests/CTS/methods/requests/search/saveSynonym.json index 1d75227329..a812b9d08e 100644 --- a/tests/CTS/methods/requests/search/saveSynonym.json +++ b/tests/CTS/methods/requests/search/saveSynonym.json @@ -5,12 +5,8 @@ "indexName": "indexName", "objectID": "id1", "synonymHit": { - "$objectName": "SynonymHit", "objectID": "id1", - "type": { - "$enumType": "SynonymType", - "value": "synonym" - }, + "type": "synonym", "synonyms": [ "car", "vehicule", diff --git a/tests/CTS/methods/requests/search/saveSynonyms.json b/tests/CTS/methods/requests/search/saveSynonyms.json index 33376641aa..37eb61cea6 100644 --- a/tests/CTS/methods/requests/search/saveSynonyms.json +++ b/tests/CTS/methods/requests/search/saveSynonyms.json @@ -5,12 +5,8 @@ "indexName": "indexName", "synonymHit": [ { - "$objectName": "SynonymHit", "objectID": "id1", - "type": { - "$enumType": "SynonymType", - "value": "synonym" - }, + "type": "synonym", "synonyms": [ "car", "vehicule", @@ -18,12 +14,8 @@ ] }, { - "$objectName": "SynonymHit", "objectID": "id2", - "type": { - "$enumType": "SynonymType", - "value": "onewaysynonym" - }, + "type": "onewaysynonym", "input": "iphone", "synonyms": [ "ephone", diff --git a/tests/CTS/methods/requests/search/search.json b/tests/CTS/methods/requests/search/search.json index ded605a9ac..59e762fc6e 100644 --- a/tests/CTS/methods/requests/search/search.json +++ b/tests/CTS/methods/requests/search/search.json @@ -4,7 +4,6 @@ "parameters": { "indexName": "indexName", "searchParams": { - "$objectName": "SearchParams", "query": "myQuery" } }, diff --git a/tests/CTS/methods/requests/search/searchDictionaryEntries.json b/tests/CTS/methods/requests/search/searchDictionaryEntries.json index b0716bfe3d..ed44e1b463 100644 --- a/tests/CTS/methods/requests/search/searchDictionaryEntries.json +++ b/tests/CTS/methods/requests/search/searchDictionaryEntries.json @@ -5,7 +5,6 @@ "parameters": { "dictionaryName": "compounds", "searchDictionaryEntriesParams": { - "$objectName": "SearchDictionaryEntriesParams", "query": "foo" } }, @@ -23,7 +22,6 @@ "parameters": { "dictionaryName": "compounds", "searchDictionaryEntriesParams": { - "$objectName": "SearchDictionaryEntriesParams", "query": "foo", "page": 4, "hitsPerPage": 2, diff --git a/tests/CTS/methods/requests/search/searchForFacetValues.json b/tests/CTS/methods/requests/search/searchForFacetValues.json index c2f8ddba90..56d7627fc5 100644 --- a/tests/CTS/methods/requests/search/searchForFacetValues.json +++ b/tests/CTS/methods/requests/search/searchForFacetValues.json @@ -18,7 +18,6 @@ "indexName": "indexName", "facetName": "facetName", "searchForFacetValuesRequest": { - "$objectName": "SearchForFacetValuesRequest", "params": "query=foo&facetFilters=['bar']", "facetQuery": "foo", "maxFacetHits": 42 diff --git a/tests/CTS/methods/requests/search/searchRules.json b/tests/CTS/methods/requests/search/searchRules.json index a45997400f..8c9a181bcd 100644 --- a/tests/CTS/methods/requests/search/searchRules.json +++ b/tests/CTS/methods/requests/search/searchRules.json @@ -4,7 +4,6 @@ "parameters": { "indexName": "indexName", "searchRulesParams": { - "$objectName": "SearchRulesParams", "query": "something" } }, diff --git a/tests/CTS/methods/requests/search/searchUserIds.json b/tests/CTS/methods/requests/search/searchUserIds.json index 471332c78d..48f9ead386 100644 --- a/tests/CTS/methods/requests/search/searchUserIds.json +++ b/tests/CTS/methods/requests/search/searchUserIds.json @@ -2,7 +2,6 @@ { "method": "searchUserIds", "parameters": { - "$objectName": "SearchUserIdsParams", "query": "test", "clusterName": "theClusterName", "page": 5, diff --git a/tests/CTS/methods/requests/search/setDictionarySettings.json b/tests/CTS/methods/requests/search/setDictionarySettings.json index fcc2cb41c1..af1148b5c0 100644 --- a/tests/CTS/methods/requests/search/setDictionarySettings.json +++ b/tests/CTS/methods/requests/search/setDictionarySettings.json @@ -3,11 +3,8 @@ "method": "setDictionarySettings", "testName": "get setDictionarySettings results with minimal parameters", "parameters": { - "$objectName": "DictionarySettingsParams", "disableStandardEntries": { - "$objectName": "StandardEntries", "plurals": { - "$objectName": "Object", "fr": false, "en": false, "ru": true @@ -32,21 +29,16 @@ "method": "setDictionarySettings", "testName": "get setDictionarySettings results with all parameters", "parameters": { - "$objectName": "DictionarySettingsParams", "disableStandardEntries": { - "$objectName": "StandardEntries", "plurals": { - "$objectName": "Object", "fr": false, "en": false, "ru": true }, "stopwords": { - "$objectName": "Object", "fr": false }, "compounds": { - "$objectName": "Object", "ru": true } } diff --git a/tests/CTS/methods/requests/search/setSettings.json b/tests/CTS/methods/requests/search/setSettings.json index 3a7a342509..ec4a635343 100644 --- a/tests/CTS/methods/requests/search/setSettings.json +++ b/tests/CTS/methods/requests/search/setSettings.json @@ -4,7 +4,6 @@ "parameters": { "indexName": "theIndexName", "indexSettings": { - "$objectName": "IndexSettings", "paginationLimitedTo": 10 }, "forwardToReplicas": true diff --git a/tests/CTS/methods/requests/search/updateApiKey.json b/tests/CTS/methods/requests/search/updateApiKey.json index cbf966a8ec..f4d1a65486 100644 --- a/tests/CTS/methods/requests/search/updateApiKey.json +++ b/tests/CTS/methods/requests/search/updateApiKey.json @@ -4,7 +4,6 @@ "parameters": { "key": "myApiKey", "apiKey": { - "$objectName": "ApiKey", "acl": [ "search", "addObject" diff --git a/tests/CTS/methods/requests/templates/java/generateParams.mustache b/tests/CTS/methods/requests/templates/java/generateParams.mustache index 0987f57fa8..539c774dbc 100644 --- a/tests/CTS/methods/requests/templates/java/generateParams.mustache +++ b/tests/CTS/methods/requests/templates/java/generateParams.mustache @@ -2,10 +2,10 @@ {{#isInteger}}int {{{key}}}{{suffix}} = {{{value}}};{{/isInteger}} {{#isDouble}}double {{{key}}}{{suffix}} = {{{value}}};{{/isDouble}} {{#isBoolean}}boolean {{{key}}}{{suffix}} = {{{value}}};{{/isBoolean}} -{{#isEnum}}{{#value}}{{{enumType}}} {{{key}}}{{suffix}} = {{{enumType}}}.fromValue("{{{value}}}");{{/value}}{{/isEnum}} +{{#isEnum}}{{{objectName}}} {{{key}}}{{suffix}} = {{{objectName}}}.fromValue("{{{value}}}");{{/isEnum}} {{#isArray}}List {{{key}}}{{suffix}} = new ArrayList(); { {{#value}}{{> generateParams}}{{parent}}{{parentSuffix}}.add({{{key}}}{{suffix}});{{/value}} }{{/isArray}} {{#isObject}}{{{objectName}}} {{{key}}}{{suffix}} = new {{{objectName}}}(); -{ {{#value}}{{> generateParams}}{{parent}}{{parentSuffix}}.set{{#capitalize}}{{{key}}}{{/capitalize}}({{{key}}}{{suffix}}); +{ {{#value}}{{> generateParams}}{{parent}}{{parentSuffix}}.set{{#lambda.titlecase}}{{{key}}}{{/lambda.titlecase}}({{{key}}}{{suffix}}); {{/value}} }{{/isObject}}{{#isFreeFormObject}}HashMap {{{key}}}{{suffix}} = new HashMap(); { {{#value}}{{> generateParams}}{{parent}}{{parentSuffix}}.put("{{{key}}}", {{{key}}}{{suffix}}); {{/value}} }{{/isFreeFormObject}} diff --git a/tests/CTS/methods/requests/templates/java/requests.mustache b/tests/CTS/methods/requests/templates/java/requests.mustache index 90f40a10bb..5b3940022f 100644 --- a/tests/CTS/methods/requests/templates/java/requests.mustache +++ b/tests/CTS/methods/requests/templates/java/requests.mustache @@ -13,7 +13,7 @@ import com.google.gson.reflect.TypeToken; import com.algolia.JSON; import com.algolia.Pair; -import com.algolia.model.*; +import com.algolia.model.search.*; import com.algolia.search.{{client}}; import com.algolia.utils.echo.*; import org.skyscreamer.jsonassert.JSONAssert; @@ -22,12 +22,10 @@ import org.skyscreamer.jsonassert.JSONCompareMode; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class {{client}}Tests { private {{client}} client; - private JSON json; @BeforeAll void init() { client = new {{client}}("appId", "apiKey", new EchoRequester()); - json = new JSON(); } {{#blocks}} @@ -38,7 +36,7 @@ class {{client}}Tests { {{#parametersWithDataType}}{{> generateParams}}{{/parametersWithDataType}} EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.{{method}}({{#parametersWithDataType}}{{{key}}}{{suffix}}{{^-last}},{{/-last}}{{/parametersWithDataType}}); + return client.{{method}}({{#parametersWithDataType}}{{#oneOfModel}}{{{.}}}.of({{{key}}}{{suffix}}){{/oneOfModel}}{{^oneOfModel}}{{{key}}}{{suffix}}{{/oneOfModel}}{{^-last}},{{/-last}}{{/parametersWithDataType}}); }); assertEquals(req.getPath(), "{{{request.path}}}"); @@ -46,12 +44,12 @@ class {{client}}Tests { {{#request.data}} assertDoesNotThrow(() -> { - JSONAssert.assertEquals("{{#escapeQuotes}}{{{request.data}}}{{/escapeQuotes}}", req.getBody(), JSONCompareMode.STRICT_ORDER); + JSONAssert.assertEquals("{{#lambda.escapequotes}}{{{request.data}}}{{/lambda.escapequotes}}", req.getBody(), JSONCompareMode.STRICT_ORDER); }); {{/request.data}} {{#request.searchParams}} - HashMap expectedQuery = json.deserialize("{{#escapeQuotes}}{{{request.searchParams}}}{{/escapeQuotes}}", new TypeToken>() {}.getType()); + HashMap expectedQuery = JSON.deserialize("{{#lambda.escapequotes}}{{{request.searchParams}}}{{/lambda.escapequotes}}", new TypeToken>() {}.getType()); List acutalQuery = req.getQueryParams(); for (Pair p : acutalQuery) { assertEquals(expectedQuery.get(p.getName()), p.getValue()); diff --git a/tests/output/java/.openapi-generator-ignore b/tests/output/java/.openapi-generator-ignore new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/output/java/src/test/java/com/algolia/methods/requests/search.test.java b/tests/output/java/src/test/java/com/algolia/methods/requests/search.test.java index af59b9db5d..28ea4f3a0d 100644 --- a/tests/output/java/src/test/java/com/algolia/methods/requests/search.test.java +++ b/tests/output/java/src/test/java/com/algolia/methods/requests/search.test.java @@ -5,7 +5,7 @@ import com.algolia.JSON; import com.algolia.Pair; -import com.algolia.model.*; +import com.algolia.model.search.*; import com.algolia.search.SearchApi; import com.algolia.utils.echo.*; import com.google.gson.reflect.TypeToken; @@ -21,49 +21,48 @@ class SearchApiTests { private SearchApi client; - private JSON json; @BeforeAll void init() { client = new SearchApi("appId", "apiKey", new EchoRequester()); - json = new JSON(); } @Test @DisplayName("addApiKey") void addApiKeyTest0() { - ApiKey param0 = new ApiKey(); + ApiKey apiKey0 = new ApiKey(); { List acl1 = new ArrayList(); { - String aclParam02 = "search"; + Acl acl_02 = Acl.fromValue("search"); - acl1.add(aclParam02); - String aclParam12 = "addObject"; + acl1.add(acl_02); - acl1.add(aclParam12); + Acl acl_12 = Acl.fromValue("addObject"); + + acl1.add(acl_12); } - param0.setAcl(acl1); + apiKey0.setAcl(acl1); String description1 = "my new api key"; - param0.setDescription(description1); + apiKey0.setDescription(description1); int validity1 = 300; - param0.setValidity(validity1); + apiKey0.setValidity(validity1); int maxQueriesPerIPPerHour1 = 100; - param0.setMaxQueriesPerIPPerHour(maxQueriesPerIPPerHour1); + apiKey0.setMaxQueriesPerIPPerHour(maxQueriesPerIPPerHour1); int maxHitsPerQuery1 = 20; - param0.setMaxHitsPerQuery(maxHitsPerQuery1); + apiKey0.setMaxHitsPerQuery(maxHitsPerQuery1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.addApiKey(param0); + return client.addApiKey(apiKey0); } ); @@ -83,19 +82,19 @@ void addApiKeyTest0() { @Test @DisplayName("addOrUpdateObject") void addOrUpdateObjectTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String objectID1 = "uniqueID"; + String objectID0 = "uniqueID"; - HashMap body1 = new HashMap(); + HashMap body0 = new HashMap(); { - String key2 = "value"; + String key1 = "value"; - body1.put("key", key2); + body0.put("key", key1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.addOrUpdateObject(indexName1, objectID1, body1); + return client.addOrUpdateObject(indexName0, objectID0, body0); } ); @@ -114,18 +113,18 @@ void addOrUpdateObjectTest0() { @Test @DisplayName("appendSource") void appendSourceTest0() { - Source param0 = new Source(); + Source source0 = new Source(); { String source1 = "theSource"; - param0.setSource(source1); + source0.setSource(source1); String description1 = "theDescription"; - param0.setDescription(description1); + source0.setDescription(description1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.appendSource(param0); + return client.appendSource(source0); } ); @@ -144,17 +143,17 @@ void appendSourceTest0() { @Test @DisplayName("assignUserId") void assignUserIdTest0() { - String xAlgoliaUserID1 = "userID"; + String xAlgoliaUserID0 = "userID"; - AssignUserIdParams assignUserIdParams1 = new AssignUserIdParams(); + AssignUserIdParams assignUserIdParams0 = new AssignUserIdParams(); { - String cluster2 = "theCluster"; + String cluster1 = "theCluster"; - assignUserIdParams1.setCluster(cluster2); + assignUserIdParams0.setCluster(cluster1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.assignUserId(xAlgoliaUserID1, assignUserIdParams1); + return client.assignUserId(xAlgoliaUserID0, assignUserIdParams0); } ); @@ -169,7 +168,7 @@ void assignUserIdTest0() { ); }); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"X-Algolia-User-ID\":\"userID\"}", new TypeToken>() {}.getType() ); @@ -182,34 +181,34 @@ void assignUserIdTest0() { @Test @DisplayName("batch") void batchTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - BatchWriteParams batchWriteParams1 = new BatchWriteParams(); + BatchWriteParams batchWriteParams0 = new BatchWriteParams(); { - List requests2 = new ArrayList(); + List requests1 = new ArrayList(); { - BatchOperation requestsParam03 = new BatchOperation(); + BatchOperation requests_02 = new BatchOperation(); { - Action action4 = Action.fromValue("delete"); + Action action3 = Action.fromValue("delete"); - requestsParam03.setAction(action4); + requests_02.setAction(action3); - HashMap body4 = new HashMap(); + HashMap body3 = new HashMap(); { - String key5 = "value"; + String key4 = "value"; - body4.put("key", key5); + body3.put("key", key4); } - requestsParam03.setBody(body4); + requests_02.setBody(body3); } - requests2.add(requestsParam03); + requests1.add(requests_02); } - batchWriteParams1.setRequests(requests2); + batchWriteParams0.setRequests(requests1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.batch(indexName1, batchWriteParams1); + return client.batch(indexName0, batchWriteParams0); } ); @@ -228,31 +227,31 @@ void batchTest0() { @Test @DisplayName("batchAssignUserIds") void batchAssignUserIdsTest0() { - String xAlgoliaUserID1 = "userID"; + String xAlgoliaUserID0 = "userID"; - BatchAssignUserIdsParams batchAssignUserIdsParams1 = new BatchAssignUserIdsParams(); + BatchAssignUserIdsParams batchAssignUserIdsParams0 = new BatchAssignUserIdsParams(); { - String cluster2 = "theCluster"; + String cluster1 = "theCluster"; - batchAssignUserIdsParams1.setCluster(cluster2); + batchAssignUserIdsParams0.setCluster(cluster1); - List users2 = new ArrayList(); + List users1 = new ArrayList(); { - String usersParam03 = "user1"; + String users_02 = "user1"; - users2.add(usersParam03); - String usersParam13 = "user2"; + users1.add(users_02); + String users_12 = "user2"; - users2.add(usersParam13); + users1.add(users_12); } - batchAssignUserIdsParams1.setUsers(users2); + batchAssignUserIdsParams0.setUsers(users1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.batchAssignUserIds( - xAlgoliaUserID1, - batchAssignUserIdsParams1 + xAlgoliaUserID0, + batchAssignUserIdsParams0 ); } ); @@ -268,7 +267,7 @@ void batchAssignUserIdsTest0() { ); }); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"X-Algolia-User-ID\":\"userID\"}", new TypeToken>() {}.getType() ); @@ -281,58 +280,58 @@ void batchAssignUserIdsTest0() { @Test @DisplayName("get batchDictionaryEntries results with minimal parameters") void batchDictionaryEntriesTest0() { - String dictionaryName1 = "compounds"; + DictionaryType dictionaryName0 = DictionaryType.fromValue("compounds"); - BatchDictionaryEntriesParams batchDictionaryEntriesParams1 = new BatchDictionaryEntriesParams(); + BatchDictionaryEntriesParams batchDictionaryEntriesParams0 = new BatchDictionaryEntriesParams(); { - List requests2 = new ArrayList(); + List requests1 = new ArrayList(); { - BatchDictionaryEntriesRequest requestsParam03 = new BatchDictionaryEntriesRequest(); + BatchDictionaryEntriesRequest requests_02 = new BatchDictionaryEntriesRequest(); { - DictionaryAction action4 = DictionaryAction.fromValue("addEntry"); + DictionaryAction action3 = DictionaryAction.fromValue("addEntry"); - requestsParam03.setAction(action4); + requests_02.setAction(action3); - DictionaryEntry body4 = new DictionaryEntry(); + DictionaryEntry body3 = new DictionaryEntry(); { - String objectID5 = "1"; + String objectID4 = "1"; - body4.setObjectID(objectID5); - String language5 = "en"; + body3.setObjectID(objectID4); + String language4 = "en"; - body4.setLanguage(language5); + body3.setLanguage(language4); } - requestsParam03.setBody(body4); + requests_02.setBody(body3); } - requests2.add(requestsParam03); + requests1.add(requests_02); - BatchDictionaryEntriesRequest requestsParam13 = new BatchDictionaryEntriesRequest(); + BatchDictionaryEntriesRequest requests_12 = new BatchDictionaryEntriesRequest(); { - DictionaryAction action4 = DictionaryAction.fromValue("deleteEntry"); + DictionaryAction action3 = DictionaryAction.fromValue("deleteEntry"); - requestsParam13.setAction(action4); + requests_12.setAction(action3); - DictionaryEntry body4 = new DictionaryEntry(); + DictionaryEntry body3 = new DictionaryEntry(); { - String objectID5 = "2"; + String objectID4 = "2"; - body4.setObjectID(objectID5); - String language5 = "fr"; + body3.setObjectID(objectID4); + String language4 = "fr"; - body4.setLanguage(language5); + body3.setLanguage(language4); } - requestsParam13.setBody(body4); + requests_12.setBody(body3); } - requests2.add(requestsParam13); + requests1.add(requests_12); } - batchDictionaryEntriesParams1.setRequests(requests2); + batchDictionaryEntriesParams0.setRequests(requests1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.batchDictionaryEntries( - dictionaryName1, - batchDictionaryEntriesParams1 + dictionaryName0, + batchDictionaryEntriesParams0 ); } ); @@ -352,130 +351,130 @@ void batchDictionaryEntriesTest0() { @Test @DisplayName("get batchDictionaryEntries results with all parameters") void batchDictionaryEntriesTest1() { - String dictionaryName1 = "compounds"; + DictionaryType dictionaryName0 = DictionaryType.fromValue("compounds"); - BatchDictionaryEntriesParams batchDictionaryEntriesParams1 = new BatchDictionaryEntriesParams(); + BatchDictionaryEntriesParams batchDictionaryEntriesParams0 = new BatchDictionaryEntriesParams(); { - boolean clearExistingDictionaryEntries2 = false; + boolean clearExistingDictionaryEntries1 = false; - batchDictionaryEntriesParams1.setClearExistingDictionaryEntries( - clearExistingDictionaryEntries2 + batchDictionaryEntriesParams0.setClearExistingDictionaryEntries( + clearExistingDictionaryEntries1 ); - List requests2 = new ArrayList(); + List requests1 = new ArrayList(); { - BatchDictionaryEntriesRequest requestsParam03 = new BatchDictionaryEntriesRequest(); + BatchDictionaryEntriesRequest requests_02 = new BatchDictionaryEntriesRequest(); { - DictionaryAction action4 = DictionaryAction.fromValue("addEntry"); + DictionaryAction action3 = DictionaryAction.fromValue("addEntry"); - requestsParam03.setAction(action4); + requests_02.setAction(action3); - DictionaryEntry body4 = new DictionaryEntry(); + DictionaryEntry body3 = new DictionaryEntry(); { - String objectID5 = "1"; + String objectID4 = "1"; - body4.setObjectID(objectID5); - String language5 = "en"; + body3.setObjectID(objectID4); + String language4 = "en"; - body4.setLanguage(language5); - String word5 = "yo"; + body3.setLanguage(language4); + String word4 = "fancy"; - body4.setWord(word5); + body3.setWord(word4); - List words5 = new ArrayList(); + List words4 = new ArrayList(); { - String wordsParam06 = "yo"; + String words_05 = "believe"; - words5.add(wordsParam06); - String wordsParam16 = "algolia"; + words4.add(words_05); + String words_15 = "algolia"; - words5.add(wordsParam16); + words4.add(words_15); } - body4.setWords(words5); + body3.setWords(words4); - List decomposition5 = new ArrayList(); + List decomposition4 = new ArrayList(); { - String decompositionParam06 = "yo"; + String decomposition_05 = "trust"; - decomposition5.add(decompositionParam06); - String decompositionParam16 = "algolia"; + decomposition4.add(decomposition_05); + String decomposition_15 = "algolia"; - decomposition5.add(decompositionParam16); + decomposition4.add(decomposition_15); } - body4.setDecomposition(decomposition5); + body3.setDecomposition(decomposition4); - DictionaryEntryState state5 = DictionaryEntryState.fromValue( + DictionaryEntryState state4 = DictionaryEntryState.fromValue( "enabled" ); - body4.setState(state5); + body3.setState(state4); } - requestsParam03.setBody(body4); + requests_02.setBody(body3); } - requests2.add(requestsParam03); + requests1.add(requests_02); - BatchDictionaryEntriesRequest requestsParam13 = new BatchDictionaryEntriesRequest(); + BatchDictionaryEntriesRequest requests_12 = new BatchDictionaryEntriesRequest(); { - DictionaryAction action4 = DictionaryAction.fromValue("deleteEntry"); + DictionaryAction action3 = DictionaryAction.fromValue("deleteEntry"); - requestsParam13.setAction(action4); + requests_12.setAction(action3); - DictionaryEntry body4 = new DictionaryEntry(); + DictionaryEntry body3 = new DictionaryEntry(); { - String objectID5 = "2"; + String objectID4 = "2"; - body4.setObjectID(objectID5); - String language5 = "fr"; + body3.setObjectID(objectID4); + String language4 = "fr"; - body4.setLanguage(language5); - String word5 = "salut"; + body3.setLanguage(language4); + String word4 = "humility"; - body4.setWord(word5); + body3.setWord(word4); - List words5 = new ArrayList(); + List words4 = new ArrayList(); { - String wordsParam06 = "salut"; + String words_05 = "candor"; - words5.add(wordsParam06); - String wordsParam16 = "algolia"; + words4.add(words_05); + String words_15 = "algolia"; - words5.add(wordsParam16); + words4.add(words_15); } - body4.setWords(words5); + body3.setWords(words4); - List decomposition5 = new ArrayList(); + List decomposition4 = new ArrayList(); { - String decompositionParam06 = "salut"; + String decomposition_05 = "grit"; - decomposition5.add(decompositionParam06); - String decompositionParam16 = "algolia"; + decomposition4.add(decomposition_05); + String decomposition_15 = "algolia"; - decomposition5.add(decompositionParam16); + decomposition4.add(decomposition_15); } - body4.setDecomposition(decomposition5); + body3.setDecomposition(decomposition4); - DictionaryEntryState state5 = DictionaryEntryState.fromValue( + DictionaryEntryState state4 = DictionaryEntryState.fromValue( "enabled" ); - body4.setState(state5); + body3.setState(state4); } - requestsParam13.setBody(body4); + requests_12.setBody(body3); } - requests2.add(requestsParam13); + requests1.add(requests_12); } - batchDictionaryEntriesParams1.setRequests(requests2); + batchDictionaryEntriesParams0.setRequests(requests1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.batchDictionaryEntries( - dictionaryName1, - batchDictionaryEntriesParams1 + dictionaryName0, + batchDictionaryEntriesParams0 ); } ); @@ -485,7 +484,7 @@ void batchDictionaryEntriesTest1() { assertDoesNotThrow(() -> { JSONAssert.assertEquals( - "{\"clearExistingDictionaryEntries\":false,\"requests\":[{\"action\":\"addEntry\",\"body\":{\"objectID\":\"1\",\"language\":\"en\",\"word\":\"yo\",\"words\":[\"yo\",\"algolia\"],\"decomposition\":[\"yo\",\"algolia\"],\"state\":\"enabled\"}},{\"action\":\"deleteEntry\",\"body\":{\"objectID\":\"2\",\"language\":\"fr\",\"word\":\"salut\",\"words\":[\"salut\",\"algolia\"],\"decomposition\":[\"salut\",\"algolia\"],\"state\":\"enabled\"}}]}", + "{\"clearExistingDictionaryEntries\":false,\"requests\":[{\"action\":\"addEntry\",\"body\":{\"objectID\":\"1\",\"language\":\"en\",\"word\":\"fancy\",\"words\":[\"believe\",\"algolia\"],\"decomposition\":[\"trust\",\"algolia\"],\"state\":\"enabled\"}},{\"action\":\"deleteEntry\",\"body\":{\"objectID\":\"2\",\"language\":\"fr\",\"word\":\"humility\",\"words\":[\"candor\",\"algolia\"],\"decomposition\":[\"grit\",\"algolia\"],\"state\":\"enabled\"}}]}", req.getBody(), JSONCompareMode.STRICT_ORDER ); @@ -495,95 +494,95 @@ void batchDictionaryEntriesTest1() { @Test @DisplayName("batchRules") void batchRulesTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - List rule1 = new ArrayList(); + List rule0 = new ArrayList(); { - Rule ruleParam02 = new Rule(); + Rule rule_01 = new Rule(); { - String objectID3 = "a-rule-id"; + String objectID2 = "a-rule-id"; - ruleParam02.setObjectID(objectID3); + rule_01.setObjectID(objectID2); - List conditions3 = new ArrayList(); + List conditions2 = new ArrayList(); { - Condition conditionsParam04 = new Condition(); + Condition conditions_03 = new Condition(); { - String pattern5 = "smartphone"; + String pattern4 = "smartphone"; - conditionsParam04.setPattern(pattern5); + conditions_03.setPattern(pattern4); - Anchoring anchoring5 = Anchoring.fromValue("contains"); + Anchoring anchoring4 = Anchoring.fromValue("contains"); - conditionsParam04.setAnchoring(anchoring5); + conditions_03.setAnchoring(anchoring4); } - conditions3.add(conditionsParam04); + conditions2.add(conditions_03); } - ruleParam02.setConditions(conditions3); + rule_01.setConditions(conditions2); - Consequence consequence3 = new Consequence(); + Consequence consequence2 = new Consequence(); { - ConsequenceParams params4 = new ConsequenceParams(); + ConsequenceParams params3 = new ConsequenceParams(); { - String filters5 = "category:smartphone"; + String filters4 = "category:smartphone"; - params4.setFilters(filters5); + params3.setFilters(filters4); } - consequence3.setParams(params4); + consequence2.setParams(params3); } - ruleParam02.setConsequence(consequence3); + rule_01.setConsequence(consequence2); } - rule1.add(ruleParam02); + rule0.add(rule_01); - Rule ruleParam12 = new Rule(); + Rule rule_11 = new Rule(); { - String objectID3 = "a-second-rule-id"; + String objectID2 = "a-second-rule-id"; - ruleParam12.setObjectID(objectID3); + rule_11.setObjectID(objectID2); - List conditions3 = new ArrayList(); + List conditions2 = new ArrayList(); { - Condition conditionsParam04 = new Condition(); + Condition conditions_03 = new Condition(); { - String pattern5 = "apple"; + String pattern4 = "apple"; - conditionsParam04.setPattern(pattern5); + conditions_03.setPattern(pattern4); - Anchoring anchoring5 = Anchoring.fromValue("contains"); + Anchoring anchoring4 = Anchoring.fromValue("contains"); - conditionsParam04.setAnchoring(anchoring5); + conditions_03.setAnchoring(anchoring4); } - conditions3.add(conditionsParam04); + conditions2.add(conditions_03); } - ruleParam12.setConditions(conditions3); + rule_11.setConditions(conditions2); - Consequence consequence3 = new Consequence(); + Consequence consequence2 = new Consequence(); { - ConsequenceParams params4 = new ConsequenceParams(); + ConsequenceParams params3 = new ConsequenceParams(); { - String filters5 = "brand:apple"; + String filters4 = "brand:apple"; - params4.setFilters(filters5); + params3.setFilters(filters4); } - consequence3.setParams(params4); + consequence2.setParams(params3); } - ruleParam12.setConsequence(consequence3); + rule_11.setConsequence(consequence2); } - rule1.add(ruleParam12); + rule0.add(rule_11); } - boolean forwardToReplicas1 = true; + boolean forwardToReplicas0 = true; - boolean clearExistingRules1 = true; + boolean clearExistingRules0 = true; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.batchRules( - indexName1, - rule1, - forwardToReplicas1, - clearExistingRules1 + indexName0, + rule0, + forwardToReplicas0, + clearExistingRules0 ); } ); @@ -599,7 +598,7 @@ void batchRulesTest0() { ); }); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"forwardToReplicas\":\"true\",\"clearExistingRules\":\"true\"}", new TypeToken>() {}.getType() ); @@ -612,10 +611,10 @@ void batchRulesTest0() { @Test @DisplayName("get browse results with minimal parameters") void browseTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.browse(indexName1); + return client.browse(indexName0); } ); @@ -626,20 +625,20 @@ void browseTest0() { @Test @DisplayName("get browse results with all parameters") void browseTest1() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - BrowseRequest browseRequest1 = new BrowseRequest(); + BrowseRequest browseRequest0 = new BrowseRequest(); { - String params2 = "query=foo&facetFilters=['bar']"; + String params1 = "query=foo&facetFilters=['bar']"; - browseRequest1.setParams(params2); - String cursor2 = "cts"; + browseRequest0.setParams(params1); + String cursor1 = "cts"; - browseRequest1.setCursor(cursor2); + browseRequest0.setCursor(cursor1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.browse(indexName1, browseRequest1); + return client.browse(indexName0, browseRequest0); } ); @@ -658,10 +657,10 @@ void browseTest1() { @Test @DisplayName("clearAllSynonyms") void clearAllSynonymsTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.clearAllSynonyms(indexName1); + return client.clearAllSynonyms(indexName0); } ); @@ -672,10 +671,10 @@ void clearAllSynonymsTest0() { @Test @DisplayName("clearObjects") void clearObjectsTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.clearObjects(indexName1); + return client.clearObjects(indexName0); } ); @@ -686,10 +685,10 @@ void clearObjectsTest0() { @Test @DisplayName("clearRules") void clearRulesTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.clearRules(indexName1); + return client.clearRules(indexName0); } ); @@ -700,10 +699,10 @@ void clearRulesTest0() { @Test @DisplayName("deleteApiKey") void deleteApiKeyTest0() { - String key1 = "myTestApiKey"; + String key0 = "myTestApiKey"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.deleteApiKey(key1); + return client.deleteApiKey(key0); } ); @@ -714,17 +713,17 @@ void deleteApiKeyTest0() { @Test @DisplayName("deleteBy") void deleteByTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - SearchParams searchParams1 = new SearchParams(); + SearchParamsObject searchParams0 = new SearchParamsObject(); { - String query2 = "testQuery"; + String query1 = "testQuery"; - searchParams1.setQuery(query2); + searchParams0.setQuery(query1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.deleteBy(indexName1, searchParams1); + return client.deleteBy(indexName0, SearchParams.of(searchParams0)); } ); @@ -743,10 +742,10 @@ void deleteByTest0() { @Test @DisplayName("deleteIndex") void deleteIndexTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.deleteIndex(indexName1); + return client.deleteIndex(indexName0); } ); @@ -757,12 +756,12 @@ void deleteIndexTest0() { @Test @DisplayName("deleteObject") void deleteObjectTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - String objectID1 = "uniqueID"; + String objectID0 = "uniqueID"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.deleteObject(indexName1, objectID1); + return client.deleteObject(indexName0, objectID0); } ); @@ -773,12 +772,12 @@ void deleteObjectTest0() { @Test @DisplayName("deleteRule") void deleteRuleTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String objectID1 = "id1"; + String objectID0 = "id1"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.deleteRule(indexName1, objectID1); + return client.deleteRule(indexName0, objectID0); } ); @@ -789,10 +788,10 @@ void deleteRuleTest0() { @Test @DisplayName("deleteSource") void deleteSourceTest0() { - String source1 = "theSource"; + String source0 = "theSource"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.deleteSource(source1); + return client.deleteSource(source0); } ); @@ -803,12 +802,12 @@ void deleteSourceTest0() { @Test @DisplayName("deleteSynonym") void deleteSynonymTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String objectID1 = "id1"; + String objectID0 = "id1"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.deleteSynonym(indexName1, objectID1); + return client.deleteSynonym(indexName0, objectID0); } ); @@ -819,10 +818,10 @@ void deleteSynonymTest0() { @Test @DisplayName("getApiKey") void getApiKeyTest0() { - String key1 = "myTestApiKey"; + String key0 = "myTestApiKey"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getApiKey(key1); + return client.getApiKey(key0); } ); @@ -857,23 +856,23 @@ void getDictionarySettingsTest0() { @Test @DisplayName("getLogs") void getLogsTest0() { - int offset1 = 5; + int offset0 = 5; - int length1 = 10; + int length0 = 10; - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - String type1 = "all"; + LogType type0 = LogType.fromValue("all"); EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getLogs(offset1, length1, indexName1, type1); + return client.getLogs(offset0, length0, indexName0, type0); } ); assertEquals(req.getPath(), "/1/logs"); assertEquals(req.getMethod(), "GET"); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"offset\":\"5\",\"length\":\"10\",\"indexName\":\"theIndexName\",\"type\":\"all\"}", new TypeToken>() {}.getType() ); @@ -886,29 +885,29 @@ void getLogsTest0() { @Test @DisplayName("getObject") void getObjectTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - String objectID1 = "uniqueID"; + String objectID0 = "uniqueID"; - List attributesToRetrieve1 = new ArrayList(); + List attributesToRetrieve0 = new ArrayList(); { - String attributesToRetrieveParam02 = "attr1"; + String attributesToRetrieve_01 = "attr1"; - attributesToRetrieve1.add(attributesToRetrieveParam02); - String attributesToRetrieveParam12 = "attr2"; + attributesToRetrieve0.add(attributesToRetrieve_01); + String attributesToRetrieve_11 = "attr2"; - attributesToRetrieve1.add(attributesToRetrieveParam12); + attributesToRetrieve0.add(attributesToRetrieve_11); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getObject(indexName1, objectID1, attributesToRetrieve1); + return client.getObject(indexName0, objectID0, attributesToRetrieve0); } ); assertEquals(req.getPath(), "/1/indexes/theIndexName/uniqueID"); assertEquals(req.getMethod(), "GET"); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"attributesToRetrieve\":\"attr1,attr2\"}", new TypeToken>() {}.getType() ); @@ -921,38 +920,38 @@ void getObjectTest0() { @Test @DisplayName("getObjects") void getObjectsTest0() { - GetObjectsParams param0 = new GetObjectsParams(); + GetObjectsParams getObjectsParams0 = new GetObjectsParams(); { List requests1 = new ArrayList(); { - MultipleGetObjectsParams requestsParam02 = new MultipleGetObjectsParams(); + MultipleGetObjectsParams requests_02 = new MultipleGetObjectsParams(); { List attributesToRetrieve3 = new ArrayList(); { - String attributesToRetrieveParam04 = "attr1"; + String attributesToRetrieve_04 = "attr1"; - attributesToRetrieve3.add(attributesToRetrieveParam04); - String attributesToRetrieveParam14 = "attr2"; + attributesToRetrieve3.add(attributesToRetrieve_04); + String attributesToRetrieve_14 = "attr2"; - attributesToRetrieve3.add(attributesToRetrieveParam14); + attributesToRetrieve3.add(attributesToRetrieve_14); } - requestsParam02.setAttributesToRetrieve(attributesToRetrieve3); + requests_02.setAttributesToRetrieve(attributesToRetrieve3); String objectID3 = "uniqueID"; - requestsParam02.setObjectID(objectID3); + requests_02.setObjectID(objectID3); String indexName3 = "theIndexName"; - requestsParam02.setIndexName(indexName3); + requests_02.setIndexName(indexName3); } - requests1.add(requestsParam02); + requests1.add(requests_02); } - param0.setRequests(requests1); + getObjectsParams0.setRequests(requests1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getObjects(param0); + return client.getObjects(getObjectsParams0); } ); @@ -971,12 +970,12 @@ void getObjectsTest0() { @Test @DisplayName("getRule") void getRuleTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String objectID1 = "id1"; + String objectID0 = "id1"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getRule(indexName1, objectID1); + return client.getRule(indexName0, objectID0); } ); @@ -987,10 +986,10 @@ void getRuleTest0() { @Test @DisplayName("getSettings") void getSettingsTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getSettings(indexName1); + return client.getSettings(indexName0); } ); @@ -1013,12 +1012,12 @@ void getSourcesTest0() { @Test @DisplayName("getSynonym") void getSynonymTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String objectID1 = "id1"; + String objectID0 = "id1"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getSynonym(indexName1, objectID1); + return client.getSynonym(indexName0, objectID0); } ); @@ -1029,12 +1028,12 @@ void getSynonymTest0() { @Test @DisplayName("getTask") void getTaskTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - int taskID1 = 123; + int taskID0 = 123; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getTask(indexName1, taskID1); + return client.getTask(indexName0, taskID0); } ); @@ -1057,10 +1056,10 @@ void getTopUserIdsTest0() { @Test @DisplayName("getUserId") void getUserIdTest0() { - String userID1 = "uniqueID"; + String userID0 = "uniqueID"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.getUserId(userID1); + return client.getUserId(userID0); } ); @@ -1071,17 +1070,17 @@ void getUserIdTest0() { @Test @DisplayName("hasPendingMappings") void hasPendingMappingsTest0() { - boolean getClusters1 = true; + boolean getClusters0 = true; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.hasPendingMappings(getClusters1); + return client.hasPendingMappings(getClusters0); } ); assertEquals(req.getPath(), "/1/clusters/mapping/pending"); assertEquals(req.getMethod(), "GET"); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"getClusters\":\"true\"}", new TypeToken>() {}.getType() ); @@ -1118,17 +1117,17 @@ void listClustersTest0() { @Test @DisplayName("listIndices") void listIndicesTest0() { - int page1 = 8; + int page0 = 8; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.listIndices(page1); + return client.listIndices(page0); } ); assertEquals(req.getPath(), "/1/indexes"); assertEquals(req.getMethod(), "GET"); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"page\":\"8\"}", new TypeToken>() {}.getType() ); @@ -1141,19 +1140,19 @@ void listIndicesTest0() { @Test @DisplayName("listUserIds") void listUserIdsTest0() { - int page1 = 8; + int page0 = 8; - int hitsPerPage1 = 100; + int hitsPerPage0 = 100; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.listUserIds(page1, hitsPerPage1); + return client.listUserIds(page0, hitsPerPage0); } ); assertEquals(req.getPath(), "/1/clusters/mapping"); assertEquals(req.getMethod(), "GET"); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"page\":\"8\",\"hitsPerPage\":\"100\"}", new TypeToken>() {}.getType() ); @@ -1166,15 +1165,15 @@ void listUserIdsTest0() { @Test @DisplayName("multipleBatch") void multipleBatchTest0() { - BatchParams param0 = new BatchParams(); + BatchParams batchParams0 = new BatchParams(); { List requests1 = new ArrayList(); { - MultipleBatchOperation requestsParam02 = new MultipleBatchOperation(); + MultipleBatchOperation requests_02 = new MultipleBatchOperation(); { Action action3 = Action.fromValue("addObject"); - requestsParam02.setAction(action3); + requests_02.setAction(action3); HashMap body3 = new HashMap(); { @@ -1182,19 +1181,19 @@ void multipleBatchTest0() { body3.put("key", key4); } - requestsParam02.setBody(body3); + requests_02.setBody(body3); String indexName3 = "theIndexName"; - requestsParam02.setIndexName(indexName3); + requests_02.setIndexName(indexName3); } - requests1.add(requestsParam02); + requests1.add(requests_02); } - param0.setRequests(requests1); + batchParams0.setRequests(requests1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.multipleBatch(param0); + return client.multipleBatch(batchParams0); } ); @@ -1213,43 +1212,43 @@ void multipleBatchTest0() { @Test @DisplayName("multipleQueries") void multipleQueriesTest0() { - MultipleQueriesParams param0 = new MultipleQueriesParams(); + MultipleQueriesParams multipleQueriesParams0 = new MultipleQueriesParams(); { List requests1 = new ArrayList(); { - MultipleQueries requestsParam02 = new MultipleQueries(); + MultipleQueries requests_02 = new MultipleQueries(); { String indexName3 = "theIndexName"; - requestsParam02.setIndexName(indexName3); + requests_02.setIndexName(indexName3); String query3 = "test"; - requestsParam02.setQuery(query3); + requests_02.setQuery(query3); MultipleQueriesType type3 = MultipleQueriesType.fromValue("facet"); - requestsParam02.setType(type3); + requests_02.setType(type3); String facet3 = "theFacet"; - requestsParam02.setFacet(facet3); + requests_02.setFacet(facet3); String params3 = "testParam"; - requestsParam02.setParams(params3); + requests_02.setParams(params3); } - requests1.add(requestsParam02); + requests1.add(requests_02); } - param0.setRequests(requests1); + multipleQueriesParams0.setRequests(requests1); MultipleQueriesStrategy strategy1 = MultipleQueriesStrategy.fromValue( "stopIfEnoughMatches" ); - param0.setStrategy(strategy1); + multipleQueriesParams0.setStrategy(strategy1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.multipleQueries(param0); + return client.multipleQueries(multipleQueriesParams0); } ); @@ -1268,32 +1267,33 @@ void multipleQueriesTest0() { @Test @DisplayName("operationIndex") void operationIndexTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - OperationIndexParams operationIndexParams1 = new OperationIndexParams(); + OperationIndexParams operationIndexParams0 = new OperationIndexParams(); { - OperationType operation2 = OperationType.fromValue("copy"); + OperationType operation1 = OperationType.fromValue("copy"); - operationIndexParams1.setOperation(operation2); - String destination2 = "dest"; + operationIndexParams0.setOperation(operation1); + String destination1 = "dest"; - operationIndexParams1.setDestination(destination2); + operationIndexParams0.setDestination(destination1); - List scope2 = new ArrayList(); + List scope1 = new ArrayList(); { - String scopeParam03 = "rules"; + ScopeType scope_02 = ScopeType.fromValue("rules"); + + scope1.add(scope_02); - scope2.add(scopeParam03); - String scopeParam13 = "settings"; + ScopeType scope_12 = ScopeType.fromValue("settings"); - scope2.add(scopeParam13); + scope1.add(scope_12); } - operationIndexParams1.setScope(scope2); + operationIndexParams0.setScope(scope1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.operationIndex(indexName1, operationIndexParams1); + return client.operationIndex(indexName0, operationIndexParams0); } ); @@ -1312,51 +1312,42 @@ void operationIndexTest0() { @Test @DisplayName("partialUpdateObject") void partialUpdateObjectTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - String objectID1 = "uniqueID"; + String objectID0 = "uniqueID"; - List stringBuiltInOperation1 = new ArrayList(); + List attributeOrBuiltInOperation0 = new ArrayList(); { - HashMap stringBuiltInOperationParam02 = new HashMap(); + HashMap attributeOrBuiltInOperation_01 = new HashMap(); { - HashMap id13 = new HashMap(); - { - String _operation4 = "AddUnique"; - - id13.put("_operation", _operation4); - String value4 = "test1"; + String id12 = "test"; - id13.put("value", value4); - } - stringBuiltInOperationParam02.put("id1", id13); - } - stringBuiltInOperation1.add(stringBuiltInOperationParam02); + attributeOrBuiltInOperation_01.put("id1", id12); - HashMap stringBuiltInOperationParam12 = new HashMap(); - { - HashMap id23 = new HashMap(); + BuiltInOperation id22 = new BuiltInOperation(); { - String _operation4 = "AddUnique"; + BuiltInOperationType operation3 = BuiltInOperationType.fromValue( + "AddUnique" + ); - id23.put("_operation", _operation4); - String value4 = "test2"; + id22.setOperation(operation3); + String value3 = "test2"; - id23.put("value", value4); + id22.setValue(value3); } - stringBuiltInOperationParam12.put("id2", id23); + attributeOrBuiltInOperation_01.put("id2", id22); } - stringBuiltInOperation1.add(stringBuiltInOperationParam12); + attributeOrBuiltInOperation0.add(attributeOrBuiltInOperation_01); } - boolean createIfNotExists1 = true; + boolean createIfNotExists0 = true; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.partialUpdateObject( - indexName1, - objectID1, - stringBuiltInOperation1, - createIfNotExists1 + indexName0, + objectID0, + attributeOrBuiltInOperation0, + createIfNotExists0 ); } ); @@ -1366,13 +1357,13 @@ void partialUpdateObjectTest0() { assertDoesNotThrow(() -> { JSONAssert.assertEquals( - "[{\"id1\":{\"_operation\":\"AddUnique\",\"value\":\"test1\"}},{\"id2\":{\"_operation\":\"AddUnique\",\"value\":\"test2\"}}]", + "[{\"id1\":\"test\",\"id2\":{\"_operation\":\"AddUnique\",\"value\":\"test2\"}}]", req.getBody(), JSONCompareMode.STRICT_ORDER ); }); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"createIfNotExists\":\"true\"}", new TypeToken>() {}.getType() ); @@ -1385,10 +1376,10 @@ void partialUpdateObjectTest0() { @Test @DisplayName("removeUserId") void removeUserIdTest0() { - String userID1 = "uniqueID"; + String userID0 = "uniqueID"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.removeUserId(userID1); + return client.removeUserId(userID0); } ); @@ -1399,22 +1390,22 @@ void removeUserIdTest0() { @Test @DisplayName("replaceSources") void replaceSourcesTest0() { - List source1 = new ArrayList(); + List source0 = new ArrayList(); { - Source sourceParam02 = new Source(); + Source source_01 = new Source(); { - String source3 = "theSource"; + String source2 = "theSource"; - sourceParam02.setSource(source3); - String description3 = "theDescription"; + source_01.setSource(source2); + String description2 = "theDescription"; - sourceParam02.setDescription(description3); + source_01.setDescription(description2); } - source1.add(sourceParam02); + source0.add(source_01); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.replaceSources(source1); + return client.replaceSources(source0); } ); @@ -1433,10 +1424,10 @@ void replaceSourcesTest0() { @Test @DisplayName("restoreApiKey") void restoreApiKeyTest0() { - String key1 = "myApiKey"; + String key0 = "myApiKey"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.restoreApiKey(key1); + return client.restoreApiKey(key0); } ); @@ -1447,20 +1438,20 @@ void restoreApiKeyTest0() { @Test @DisplayName("saveObject") void saveObjectTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - HashMap body1 = new HashMap(); + HashMap body0 = new HashMap(); { - String objectID2 = "id"; + String objectID1 = "id"; - body1.put("objectID", objectID2); - String test2 = "val"; + body0.put("objectID", objectID1); + String test1 = "val"; - body1.put("test", test2); + body0.put("test", test1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.saveObject(indexName1, body1); + return client.saveObject(indexName0, body0); } ); @@ -1479,54 +1470,54 @@ void saveObjectTest0() { @Test @DisplayName("saveRule") void saveRuleTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String objectID1 = "id1"; + String objectID0 = "id1"; - Rule rule1 = new Rule(); + Rule rule0 = new Rule(); { - String objectID2 = "id1"; + String objectID1 = "id1"; - rule1.setObjectID(objectID2); + rule0.setObjectID(objectID1); - List conditions2 = new ArrayList(); + List conditions1 = new ArrayList(); { - Condition conditionsParam03 = new Condition(); + Condition conditions_02 = new Condition(); { - String pattern4 = "apple"; + String pattern3 = "apple"; - conditionsParam03.setPattern(pattern4); + conditions_02.setPattern(pattern3); - Anchoring anchoring4 = Anchoring.fromValue("contains"); + Anchoring anchoring3 = Anchoring.fromValue("contains"); - conditionsParam03.setAnchoring(anchoring4); + conditions_02.setAnchoring(anchoring3); } - conditions2.add(conditionsParam03); + conditions1.add(conditions_02); } - rule1.setConditions(conditions2); + rule0.setConditions(conditions1); - Consequence consequence2 = new Consequence(); + Consequence consequence1 = new Consequence(); { - ConsequenceParams params3 = new ConsequenceParams(); + ConsequenceParams params2 = new ConsequenceParams(); { - String filters4 = "brand:apple"; + String filters3 = "brand:apple"; - params3.setFilters(filters4); + params2.setFilters(filters3); } - consequence2.setParams(params3); + consequence1.setParams(params2); } - rule1.setConsequence(consequence2); + rule0.setConsequence(consequence1); } - boolean forwardToReplicas1 = true; + boolean forwardToReplicas0 = true; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.saveRule( - indexName1, - objectID1, - rule1, - forwardToReplicas1 + indexName0, + objectID0, + rule0, + forwardToReplicas0 ); } ); @@ -1542,7 +1533,7 @@ void saveRuleTest0() { ); }); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"forwardToReplicas\":\"true\"}", new TypeToken>() {}.getType() ); @@ -1555,44 +1546,44 @@ void saveRuleTest0() { @Test @DisplayName("saveSynonym") void saveSynonymTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String objectID1 = "id1"; + String objectID0 = "id1"; - SynonymHit synonymHit1 = new SynonymHit(); + SynonymHit synonymHit0 = new SynonymHit(); { - String objectID2 = "id1"; + String objectID1 = "id1"; - synonymHit1.setObjectID(objectID2); + synonymHit0.setObjectID(objectID1); - SynonymType type2 = SynonymType.fromValue("synonym"); + SynonymType type1 = SynonymType.fromValue("synonym"); - synonymHit1.setType(type2); + synonymHit0.setType(type1); - List synonyms2 = new ArrayList(); + List synonyms1 = new ArrayList(); { - String synonymsParam03 = "car"; + String synonyms_02 = "car"; - synonyms2.add(synonymsParam03); - String synonymsParam13 = "vehicule"; + synonyms1.add(synonyms_02); + String synonyms_12 = "vehicule"; - synonyms2.add(synonymsParam13); - String synonymsParam23 = "auto"; + synonyms1.add(synonyms_12); + String synonyms_22 = "auto"; - synonyms2.add(synonymsParam23); + synonyms1.add(synonyms_22); } - synonymHit1.setSynonyms(synonyms2); + synonymHit0.setSynonyms(synonyms1); } - boolean forwardToReplicas1 = true; + boolean forwardToReplicas0 = true; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.saveSynonym( - indexName1, - objectID1, - synonymHit1, - forwardToReplicas1 + indexName0, + objectID0, + synonymHit0, + forwardToReplicas0 ); } ); @@ -1608,7 +1599,7 @@ void saveSynonymTest0() { ); }); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"forwardToReplicas\":\"true\"}", new TypeToken>() {}.getType() ); @@ -1621,78 +1612,78 @@ void saveSynonymTest0() { @Test @DisplayName("saveSynonyms") void saveSynonymsTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - List synonymHit1 = new ArrayList(); + List synonymHit0 = new ArrayList(); { - SynonymHit synonymHitParam02 = new SynonymHit(); + SynonymHit synonymHit_01 = new SynonymHit(); { - String objectID3 = "id1"; + String objectID2 = "id1"; - synonymHitParam02.setObjectID(objectID3); + synonymHit_01.setObjectID(objectID2); - SynonymType type3 = SynonymType.fromValue("synonym"); + SynonymType type2 = SynonymType.fromValue("synonym"); - synonymHitParam02.setType(type3); + synonymHit_01.setType(type2); - List synonyms3 = new ArrayList(); + List synonyms2 = new ArrayList(); { - String synonymsParam04 = "car"; + String synonyms_03 = "car"; - synonyms3.add(synonymsParam04); - String synonymsParam14 = "vehicule"; + synonyms2.add(synonyms_03); + String synonyms_13 = "vehicule"; - synonyms3.add(synonymsParam14); - String synonymsParam24 = "auto"; + synonyms2.add(synonyms_13); + String synonyms_23 = "auto"; - synonyms3.add(synonymsParam24); + synonyms2.add(synonyms_23); } - synonymHitParam02.setSynonyms(synonyms3); + synonymHit_01.setSynonyms(synonyms2); } - synonymHit1.add(synonymHitParam02); + synonymHit0.add(synonymHit_01); - SynonymHit synonymHitParam12 = new SynonymHit(); + SynonymHit synonymHit_11 = new SynonymHit(); { - String objectID3 = "id2"; + String objectID2 = "id2"; - synonymHitParam12.setObjectID(objectID3); + synonymHit_11.setObjectID(objectID2); - SynonymType type3 = SynonymType.fromValue("onewaysynonym"); + SynonymType type2 = SynonymType.fromValue("onewaysynonym"); - synonymHitParam12.setType(type3); - String input3 = "iphone"; + synonymHit_11.setType(type2); + String input2 = "iphone"; - synonymHitParam12.setInput(input3); + synonymHit_11.setInput(input2); - List synonyms3 = new ArrayList(); + List synonyms2 = new ArrayList(); { - String synonymsParam04 = "ephone"; + String synonyms_03 = "ephone"; - synonyms3.add(synonymsParam04); - String synonymsParam14 = "aphone"; + synonyms2.add(synonyms_03); + String synonyms_13 = "aphone"; - synonyms3.add(synonymsParam14); - String synonymsParam24 = "yphone"; + synonyms2.add(synonyms_13); + String synonyms_23 = "yphone"; - synonyms3.add(synonymsParam24); + synonyms2.add(synonyms_23); } - synonymHitParam12.setSynonyms(synonyms3); + synonymHit_11.setSynonyms(synonyms2); } - synonymHit1.add(synonymHitParam12); + synonymHit0.add(synonymHit_11); } - boolean forwardToReplicas1 = true; + boolean forwardToReplicas0 = true; - boolean replaceExistingSynonyms1 = false; + boolean replaceExistingSynonyms0 = false; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.saveSynonyms( - indexName1, - synonymHit1, - forwardToReplicas1, - replaceExistingSynonyms1 + indexName0, + synonymHit0, + forwardToReplicas0, + replaceExistingSynonyms0 ); } ); @@ -1708,7 +1699,7 @@ void saveSynonymsTest0() { ); }); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"forwardToReplicas\":\"true\",\"replaceExistingSynonyms\":\"false\"}", new TypeToken>() {}.getType() ); @@ -1721,17 +1712,17 @@ void saveSynonymsTest0() { @Test @DisplayName("search") void searchTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - SearchParams searchParams1 = new SearchParams(); + SearchParamsObject searchParams0 = new SearchParamsObject(); { - String query2 = "myQuery"; + String query1 = "myQuery"; - searchParams1.setQuery(query2); + searchParams0.setQuery(query1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.search(indexName1, searchParams1); + return client.search(indexName0, SearchParams.of(searchParams0)); } ); @@ -1750,19 +1741,19 @@ void searchTest0() { @Test @DisplayName("get searchDictionaryEntries results with minimal parameters") void searchDictionaryEntriesTest0() { - String dictionaryName1 = "compounds"; + DictionaryType dictionaryName0 = DictionaryType.fromValue("compounds"); - SearchDictionaryEntriesParams searchDictionaryEntriesParams1 = new SearchDictionaryEntriesParams(); + SearchDictionaryEntriesParams searchDictionaryEntriesParams0 = new SearchDictionaryEntriesParams(); { - String query2 = "foo"; + String query1 = "foo"; - searchDictionaryEntriesParams1.setQuery(query2); + searchDictionaryEntriesParams0.setQuery(query1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.searchDictionaryEntries( - dictionaryName1, - searchDictionaryEntriesParams1 + dictionaryName0, + searchDictionaryEntriesParams0 ); } ); @@ -1782,30 +1773,30 @@ void searchDictionaryEntriesTest0() { @Test @DisplayName("get searchDictionaryEntries results with all parameters") void searchDictionaryEntriesTest1() { - String dictionaryName1 = "compounds"; + DictionaryType dictionaryName0 = DictionaryType.fromValue("compounds"); - SearchDictionaryEntriesParams searchDictionaryEntriesParams1 = new SearchDictionaryEntriesParams(); + SearchDictionaryEntriesParams searchDictionaryEntriesParams0 = new SearchDictionaryEntriesParams(); { - String query2 = "foo"; + String query1 = "foo"; - searchDictionaryEntriesParams1.setQuery(query2); + searchDictionaryEntriesParams0.setQuery(query1); - int page2 = 4; + int page1 = 4; - searchDictionaryEntriesParams1.setPage(page2); + searchDictionaryEntriesParams0.setPage(page1); - int hitsPerPage2 = 2; + int hitsPerPage1 = 2; - searchDictionaryEntriesParams1.setHitsPerPage(hitsPerPage2); - String language2 = "fr"; + searchDictionaryEntriesParams0.setHitsPerPage(hitsPerPage1); + String language1 = "fr"; - searchDictionaryEntriesParams1.setLanguage(language2); + searchDictionaryEntriesParams0.setLanguage(language1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.searchDictionaryEntries( - dictionaryName1, - searchDictionaryEntriesParams1 + dictionaryName0, + searchDictionaryEntriesParams0 ); } ); @@ -1825,12 +1816,12 @@ void searchDictionaryEntriesTest1() { @Test @DisplayName("get searchForFacetValues results with minimal parameters") void searchForFacetValuesTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String facetName1 = "facetName"; + String facetName0 = "facetName"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.searchForFacetValues(indexName1, facetName1); + return client.searchForFacetValues(indexName0, facetName0); } ); @@ -1841,29 +1832,29 @@ void searchForFacetValuesTest0() { @Test @DisplayName("get searchForFacetValues results with all parameters") void searchForFacetValuesTest1() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - String facetName1 = "facetName"; + String facetName0 = "facetName"; - SearchForFacetValuesRequest searchForFacetValuesRequest1 = new SearchForFacetValuesRequest(); + SearchForFacetValuesRequest searchForFacetValuesRequest0 = new SearchForFacetValuesRequest(); { - String params2 = "query=foo&facetFilters=['bar']"; + String params1 = "query=foo&facetFilters=['bar']"; - searchForFacetValuesRequest1.setParams(params2); - String facetQuery2 = "foo"; + searchForFacetValuesRequest0.setParams(params1); + String facetQuery1 = "foo"; - searchForFacetValuesRequest1.setFacetQuery(facetQuery2); + searchForFacetValuesRequest0.setFacetQuery(facetQuery1); - int maxFacetHits2 = 42; + int maxFacetHits1 = 42; - searchForFacetValuesRequest1.setMaxFacetHits(maxFacetHits2); + searchForFacetValuesRequest0.setMaxFacetHits(maxFacetHits1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.searchForFacetValues( - indexName1, - facetName1, - searchForFacetValuesRequest1 + indexName0, + facetName0, + searchForFacetValuesRequest0 ); } ); @@ -1883,17 +1874,17 @@ void searchForFacetValuesTest1() { @Test @DisplayName("searchRules") void searchRulesTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; - SearchRulesParams searchRulesParams1 = new SearchRulesParams(); + SearchRulesParams searchRulesParams0 = new SearchRulesParams(); { - String query2 = "something"; + String query1 = "something"; - searchRulesParams1.setQuery(query2); + searchRulesParams0.setQuery(query1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.searchRules(indexName1, searchRulesParams1); + return client.searchRules(indexName0, searchRulesParams0); } ); @@ -1912,10 +1903,10 @@ void searchRulesTest0() { @Test @DisplayName("searchSynonyms") void searchSynonymsTest0() { - String indexName1 = "indexName"; + String indexName0 = "indexName"; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.searchSynonyms(indexName1); + return client.searchSynonyms(indexName0); } ); @@ -1926,26 +1917,26 @@ void searchSynonymsTest0() { @Test @DisplayName("searchUserIds") void searchUserIdsTest0() { - SearchUserIdsParams param0 = new SearchUserIdsParams(); + SearchUserIdsParams searchUserIdsParams0 = new SearchUserIdsParams(); { String query1 = "test"; - param0.setQuery(query1); + searchUserIdsParams0.setQuery(query1); String clusterName1 = "theClusterName"; - param0.setClusterName(clusterName1); + searchUserIdsParams0.setClusterName(clusterName1); int page1 = 5; - param0.setPage(page1); + searchUserIdsParams0.setPage(page1); int hitsPerPage1 = 10; - param0.setHitsPerPage(hitsPerPage1); + searchUserIdsParams0.setHitsPerPage(hitsPerPage1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.searchUserIds(param0); + return client.searchUserIds(searchUserIdsParams0); } ); @@ -1964,7 +1955,7 @@ void searchUserIdsTest0() { @Test @DisplayName("get setDictionarySettings results with minimal parameters") void setDictionarySettingsTest0() { - DictionarySettingsParams param0 = new DictionarySettingsParams(); + DictionarySettingsParams dictionarySettingsParams0 = new DictionarySettingsParams(); { StandardEntries disableStandardEntries1 = new StandardEntries(); { @@ -1984,11 +1975,13 @@ void setDictionarySettingsTest0() { } disableStandardEntries1.setPlurals(plurals2); } - param0.setDisableStandardEntries(disableStandardEntries1); + dictionarySettingsParams0.setDisableStandardEntries( + disableStandardEntries1 + ); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.setDictionarySettings(param0); + return client.setDictionarySettings(dictionarySettingsParams0); } ); @@ -2007,7 +2000,7 @@ void setDictionarySettingsTest0() { @Test @DisplayName("get setDictionarySettings results with all parameters") void setDictionarySettingsTest1() { - DictionarySettingsParams param0 = new DictionarySettingsParams(); + DictionarySettingsParams dictionarySettingsParams0 = new DictionarySettingsParams(); { StandardEntries disableStandardEntries1 = new StandardEntries(); { @@ -2043,11 +2036,13 @@ void setDictionarySettingsTest1() { } disableStandardEntries1.setCompounds(compounds2); } - param0.setDisableStandardEntries(disableStandardEntries1); + dictionarySettingsParams0.setDisableStandardEntries( + disableStandardEntries1 + ); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.setDictionarySettings(param0); + return client.setDictionarySettings(dictionarySettingsParams0); } ); @@ -2066,22 +2061,22 @@ void setDictionarySettingsTest1() { @Test @DisplayName("setSettings") void setSettingsTest0() { - String indexName1 = "theIndexName"; + String indexName0 = "theIndexName"; - IndexSettings indexSettings1 = new IndexSettings(); + IndexSettings indexSettings0 = new IndexSettings(); { - int paginationLimitedTo2 = 10; + int paginationLimitedTo1 = 10; - indexSettings1.setPaginationLimitedTo(paginationLimitedTo2); + indexSettings0.setPaginationLimitedTo(paginationLimitedTo1); } - boolean forwardToReplicas1 = true; + boolean forwardToReplicas0 = true; EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { return client.setSettings( - indexName1, - indexSettings1, - forwardToReplicas1 + indexName0, + indexSettings0, + forwardToReplicas0 ); } ); @@ -2097,7 +2092,7 @@ void setSettingsTest0() { ); }); - HashMap expectedQuery = json.deserialize( + HashMap expectedQuery = JSON.deserialize( "{\"forwardToReplicas\":\"true\"}", new TypeToken>() {}.getType() ); @@ -2110,37 +2105,38 @@ void setSettingsTest0() { @Test @DisplayName("updateApiKey") void updateApiKeyTest0() { - String key1 = "myApiKey"; + String key0 = "myApiKey"; - ApiKey apiKey1 = new ApiKey(); + ApiKey apiKey0 = new ApiKey(); { - List acl2 = new ArrayList(); + List acl1 = new ArrayList(); { - String aclParam03 = "search"; + Acl acl_02 = Acl.fromValue("search"); + + acl1.add(acl_02); - acl2.add(aclParam03); - String aclParam13 = "addObject"; + Acl acl_12 = Acl.fromValue("addObject"); - acl2.add(aclParam13); + acl1.add(acl_12); } - apiKey1.setAcl(acl2); + apiKey0.setAcl(acl1); - int validity2 = 300; + int validity1 = 300; - apiKey1.setValidity(validity2); + apiKey0.setValidity(validity1); - int maxQueriesPerIPPerHour2 = 100; + int maxQueriesPerIPPerHour1 = 100; - apiKey1.setMaxQueriesPerIPPerHour(maxQueriesPerIPPerHour2); + apiKey0.setMaxQueriesPerIPPerHour(maxQueriesPerIPPerHour1); - int maxHitsPerQuery2 = 20; + int maxHitsPerQuery1 = 20; - apiKey1.setMaxHitsPerQuery(maxHitsPerQuery2); + apiKey0.setMaxHitsPerQuery(maxHitsPerQuery1); } EchoResponseInterface req = (EchoResponseInterface) assertDoesNotThrow(() -> { - return client.updateApiKey(key1, apiKey1); + return client.updateApiKey(key0, apiKey0); } ); diff --git a/tests/output/javascript/src/methods/requests/search.test.ts b/tests/output/javascript/src/methods/requests/search.test.ts index 089e67dcb2..125edae37e 100644 --- a/tests/output/javascript/src/methods/requests/search.test.ts +++ b/tests/output/javascript/src/methods/requests/search.test.ts @@ -148,9 +148,9 @@ describe('batchDictionaryEntries', () => { body: { objectID: '1', language: 'en', - word: 'yo', - words: ['yo', 'algolia'], - decomposition: ['yo', 'algolia'], + word: 'fancy', + words: ['believe', 'algolia'], + decomposition: ['trust', 'algolia'], state: 'enabled', }, }, @@ -159,9 +159,9 @@ describe('batchDictionaryEntries', () => { body: { objectID: '2', language: 'fr', - word: 'salut', - words: ['salut', 'algolia'], - decomposition: ['salut', 'algolia'], + word: 'humility', + words: ['candor', 'algolia'], + decomposition: ['grit', 'algolia'], state: 'enabled', }, }, @@ -179,9 +179,9 @@ describe('batchDictionaryEntries', () => { body: { objectID: '1', language: 'en', - word: 'yo', - words: ['yo', 'algolia'], - decomposition: ['yo', 'algolia'], + word: 'fancy', + words: ['believe', 'algolia'], + decomposition: ['trust', 'algolia'], state: 'enabled', }, }, @@ -190,9 +190,9 @@ describe('batchDictionaryEntries', () => { body: { objectID: '2', language: 'fr', - word: 'salut', - words: ['salut', 'algolia'], - decomposition: ['salut', 'algolia'], + word: 'humility', + words: ['candor', 'algolia'], + decomposition: ['grit', 'algolia'], state: 'enabled', }, }, @@ -747,9 +747,8 @@ describe('partialUpdateObject', () => { const req = (await client.partialUpdateObject({ indexName: 'theIndexName', objectID: 'uniqueID', - stringBuiltInOperation: [ - { id1: { _operation: 'AddUnique', value: 'test1' } }, - { id2: { _operation: 'AddUnique', value: 'test2' } }, + attributeOrBuiltInOperation: [ + { id1: 'test', id2: { _operation: 'AddUnique', value: 'test2' } }, ], createIfNotExists: true, })) as unknown as EchoResponse; @@ -757,8 +756,7 @@ describe('partialUpdateObject', () => { expect(req.path).toEqual('/1/indexes/theIndexName/uniqueID/partial'); expect(req.method).toEqual('POST'); expect(req.data).toEqual([ - { id1: { _operation: 'AddUnique', value: 'test1' } }, - { id2: { _operation: 'AddUnique', value: 'test2' } }, + { id1: 'test', id2: { _operation: 'AddUnique', value: 'test2' } }, ]); expect(req.searchParams).toEqual({ createIfNotExists: 'true' }); }); diff --git a/tests/output/javascript/tsconfig.json b/tests/output/javascript/tsconfig.json index c5cb759b73..4e3e73f4b3 100644 --- a/tests/output/javascript/tsconfig.json +++ b/tests/output/javascript/tsconfig.json @@ -1,5 +1,5 @@ { - "extends": "../../../base.tsconfig.json", + "extends": "../../../config/base.tsconfig.json", "compilerOptions": { "typeRoots": ["../../../node_modules/@types"], "types": ["node", "jest"], diff --git a/website/docs/commonTestSuite.md b/website/docs/commonTestSuite.md index 5497bd402c..5cc67b510a 100644 --- a/website/docs/commonTestSuite.md +++ b/website/docs/commonTestSuite.md @@ -48,12 +48,7 @@ The test generation script requires a JSON file name from the `operationId` (e.g "parameters": { "indexName": "testIndex", "searchParam": { - "$objectName": "the name of the object for strongly type language, should be on every 'object' type (can be 'Object' if free-form)", - "query": "the string to search", - "acl": { - "$enumType": "the name of the enum object if marked as enum in the spec", - "value": "the string value of the enum" - } + "query": "the string to search" } }, "request": { @@ -66,8 +61,6 @@ The test generation script requires a JSON file name from the `operationId` (e.g ``` And that's it! If the name of the file matches a real `operationId` in the spec, then a test will be generated. -Don't forget to add `$objectName` and `$enumType` when necessary, otherwise typed language will fail to generate tests. - ## How to add a new language - Create a template in `test/CTS/templates//requests.mustache` that parses an array of tests into the test framework of choice